Random quote share HELP!

Random quote share HELP!
0.0 0

#1

My code to share the quote does not work, it open a new window but does not add the quote. This is my code:

var currentQuote ="";
function myQuote () {
  var randomNumber = Math.floor(Math.random() * (quotes.length));
  document.getElementById("quote").innerHTML = quotes[randomNumber];
  var currentQuote =  $("#quote").text();
}

var shareMyQuote = function() {
  window.open('https://twitter.com/intent/tweet?&text=' + currentQuote);
   };

Am I doing something wrong??


#2

You’re never setting currentQuote to anything but “”.


#3

You’re shadowing your global variable with a local declaration.

Also, (relatedly!) avoid global variables where possible.


#4

If you declare a variable in a function, the value will be that only in the function. To give a value to a variable that you declare global you dont need to use var.

So:

currentQuote =  $("#quote").text();

#5

Thanks for your answer!


#6

Thanks for your answer but how can I do that, sorry I am new.


#7

I fixed! thank you for your help!


#8

Glad you got it! :slight_smile:

For reference, @stefalber and myself were saying the same thing: I was explaining the why and he was explaining the how.

Understanding how variables are “scoped” is a pretty important concept in programming, so it’s good to hit this snag and then overcome it.