I can’t seem to get my tweet text to come up as anything but undefined, even though I’ve declared the variables outside my getQuote function! My quote function works just fine. Here’s my codepen:
http://codepen.io/711levi711/pen/KaNKgP.
Thank you I really appreciate the help! Alot of other people that had my problem seemed to fix it by declaring the variables outside of the function, but its still not working for me for some reason.
Hi @711levi711
The problem you’re having is related to the scope of getQuote
.
Because your defining ranQuote again inside the getQuote function, it’s assigning the random quote to that variable inside the function making it local to getQuote and not available outside of it. So when the button reads ranQuote, it will always be undefined.
Easiest way to fix it is remove the var declaration from ranQuote and ranAuthor inside the getQuote function, that way it will overwrite the variables in it’s upper scope, the ready function.
$(document).ready(function(){
var random;
var ranQuote;
var ranAuthor;
getQuote();
function getQuote(){
var quotes = [...];
var random = Math.floor(Math.random()*quotes.length);
// Now these two will override the variables in the ready function and be available to the tweet button.
ranQuote = quotes[random];
ranAuthor = author[random];
$(".quote").text(ranQuote);
$(".author").text(ranAuthor);
}
$('#tweet').on("click", function(){
window.open("https://twitter.com/intent/tweet?text="+ranQuote)
});
{...}
})
I recommend you look up how scope works in JavaScript as it’s quite an essential feature (and I probably explained it poorly ). This link should help https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/
3 Likes
Thank you so much I get it now!!
1 Like