Aharon Hyman Aharon Hyman - 1 year ago 100
Javascript Question

Tweeting a quote

I have coded a random quote generator and want to be able to share the quote to twitter.
by trying to tweet the function it is calling up the whole function to twitter and not the quote generated by the code. Any pointers will be much appreciated.

function getQuote(){
var arrayLength = quoteArray.length; //number of entries in array
var randomValue = Math.floor(Math.random()*arrayLength);
var newQuoteY = quoteArray[randomValue].yiddish;
var newQuoteE = quoteArray[randomValue].translation;



window.open("https://twitter.com/intent/tweet?text=" + getQuote);

Answer Source

The statement

window.open("https://twitter.com/intent/tweet?text=" + getQuote);

is actually appending the function itself to the URI. JavaScript compensates by taking the string form, which in this case is more or less the exact declaration you made for getQuote, albeit as a string.

You may have meant the following:

window.open("https://twitter.com/intent/tweet?text=" + getQuote());

In this case you are still going to encounter an error, as getQuote does not have a return value, and thus the tweet will simply say undefined. To correct this, you'll need to return a string in getQuote. Alternatively, you could have newQuoteY and newQuoteE be declared outside getQuote, but still set by it. This would allow for something like the following, wherein the currently displayed Yiddish quote is tweeted.

window.open("https://twitter.com/intent/tweet?text=" + newQuoteY);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download