Codes316 Codes316 - 1 year ago 65
Javascript Question

Undefined value when passing text to twitter web intent

I have JQuery code that passes a quote (which is randomly generated when a button is clicked) to twitter. However, when you open the new window to tweet the quote it displays a value of undefined as oppose to the actual quote.

Here is the Code:

var result;
function getQuotes(){

var quotes = [ "Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.-\n Buddha",
"Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.\n-Unknown",
"To be happy, we must not be too concerned with others.\n-Albert Camus",
"If you want happiness for an hour — take a nap.If you want happiness for a day — go fishing.If you want happiness for a year — inherit a fortune.If you want happiness for a lifetime — help someone else."]

var result = quotes[Math.floor(Math.random() * quotes.length)];

document.getElementById("stuff").innerHTML = result;


$(document).on('click', '#quotes', function() {


Here is a link to the codepen:

Answer Source

You have 2 different result variables due to using var twice. The only one that gets a value set is the one that is local inside getQuotes()

The other declared outside getQuotes() is always undefined.

Try changing

var result = quotes[Math.floor(Math.random() * quotes.length)];


result = quotes[Math.floor(Math.random() * quotes.length)];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download