YoungCoder YoungCoder - 4 years ago 83
CSS Question

Button not properly tweeting text

I have this codePen that is a random quote generator.
I also have a tweet button that should tweet the quote generated.
Currently when pressing it, it tweets another random quote, not the current quote displayed. Here is the function:

$(".twitter-share-button").click(function(){
$(this).attr("href", 'https://twitter.com/intent/tweet?text=' + randomNumber);
});

function tweetIt(){
var randomNumber = Math.floor(Math.random() * (quotes.length));
window.open("https://twitter.com/intent/tweet?text=" + quotes[randomNumber]);
}


I tried solving this by selecting the current ID the quote is in but to no avail:

function tweetIt(){
var tweet = document.getElementById('quote').value;
window.open("https://twitter.com/intent/tweet?text=" + quotes[randomNumber]);
};


Any help with this would be greatly appreciated.

Answer Source

You are storing your current quote within an element with the id of "quoteDisplay":

function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
    // The content for your tweet is being set here
    document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
};

So you'll need to target the innerText property for that particular element if you want to tweet the current quote :

function tweetIt(){
  // Get the contents of your current tweet
  var tweet = document.getElementById('quoteDisplay').innerText;
  // Open a new window with that tweet content
  window.open("https://twitter.com/intent/tweet?text=" + tweet);
};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download