0

I would like to use the same var randomQuote for all 3 functions (newQuote, postFB and tweet) and that does not seem to work.

If I put it inside the newQuote function only this function will work, if only outside - only share functions work and newQuote will only change the quote once on click (?).

The only way I can make all 3 functions to work is if I repeat it - one inside and one outside the newQuote function - is there any way to make it “DRY-er” ?

var randomQuote = Math.floor(Math.random() * (quotes.length)); //outside 
document.getElementById("refresh").onclick = newQuote;
 function newQuote() { 
var randomQuote = Math.floor(Math.random() * (quotes.length)); //inside


document.getElementById("facebook").onclick = postFB; 
function postFB() {
var url = "http://www.facebook.com/sharer/sharer.php?u=" + encodeURIComponent(quotes[randomQuote]);
  window.open(url);
}
  • did not include twitter function here - same idea as FB

any suggestions what I'm ( a beginner) doing wrong? Thank you in advance!

AsiaKo
  • 1
  • Your newQuote function call should have parentheses for the refresh onclick event. Also, your newQuote function needs a closing curly brace. As for accessing randomQuote inside newQuote after declaring it outside... just pass randomQuote to newQuote as an argument and do what you need to with it inside the function. – SidTheBeard Jun 20 '17 at 23:12
  • thank you for reply! newQuote with parenthesis?hmm - js book: "Unlike inline event-handling, the function name following the "=" isn't in quotes /no parenthesis following function name" / I tried this anyway- did not work / /missing curly bracket - just did not copied here /chrome console is quite helpful with finding errors like this. not sure if i understand “passing and doing what i have to do with the function” - tried to pass as parameter - messed up my pics/ the only way it works if i repeat myself with this one line of code:( code link https://codepen.io/AsiaKo/pen/ybgxQY – AsiaKo Jun 21 '17 at 00:55

1 Answers1

0

Using let instead of var to declare your variables will probably fix your issue. The difference between these two is described in detail here; the relevant idea (taken from the linked post) is that

var is scoped to the nearest function block and let is scoped to the nearest enclosing block (both are global if outside any block), which can be smaller than a function block.

J. Chen
  • 367
  • 1
  • 7
  • thank you for the reply ! I did try let before - did not work / same as with var only share functions seem to work / here is entire code: https://codepen.io/AsiaKo/pen/ybgxQY – AsiaKo Jun 21 '17 at 00:33