Tweet button on quote machine project, help needed

Tweet button on quote machine project, help needed
0

#1

I am stuck with my quote generator’s twitter button. The quote machine seems to be working but I can’t seem to figure out how to make the twitter post the current quote&author I have on the page. I am using vanilla JS and would prefer to stick to it. Here is the codepen link: https://codepen.io/elnurad/pen/vaZbXG/

It might not work so well on mobile phones since I haven’t touched its responsive design part yet. Focusing on its functionality first.

Thanks!


#2

If you have the current quote and author stored in variables then you can concatenate those onto the end of your twitter URL.

Something like

var twitterURL = "https://twitter.com/intent/tweet?text=" + quoteVariable + " - " + authorVariable

Then use the twitterURL as the href on your button.

Hope that helps


#3

Thanks for your answer, @camelcamper! I think my problem is that I don’t quite understand how to store the fetch data return (data.author/data.quote) in a global variable since it is returned inside of a fetch call. I did this:

var url = "https://talaikis.com/api/quotes/random/";
  fetch(url)
  .then(function(response){
    return response.json();
  })
  .then(function(data){
    var quoteVar = data.quote; 
    text.textContent = quoteVar;
    var authorVar = data.author;
    author.textContent = authorVar;
  })
  .catch(function(){
    console.log("The request generated an error.")
  })

But as expected, my variables are not accessible outside of this call so when I use them for my twitter button it tells me that they are not defined. What am I doing wrong?

Thanks for your help!


#4

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Anything you want to do with the data returned should be performed in the second then. You can always create a function which receives data received from the second then, but you must call it from inside the then. Fetch is asynchronous, so it also other code (after the fetch) to run before any data is received back from the fetch call. That is why anytime you try to reference global variables after the fetch which you have assigned values inside the second then still do not have those fetched values.


#5

Thanks for all the feedback and instructions. My tweet button seems to be working so your input really helped!