Random Quote Machine Help!

I’m having trouble getting my JS file to run properly. I’ve tried watching a few tutorials without any luck. Any recommendations would be great. Thank you!

Hi, Randell thanks for the reply. I’ve tried what you recommended and am still having difficulties.

Hey, so there are a few things wrong here.

  1. On line 5, you have this line of code:
    var num = Math.floor((Math.random()*quotes.length));

See where you have quotes.length? quotes is not defined anywhere. Your quotes array is called text

  1. Within randQuote() you declare 2 variables called randomQuote and randomAuthor. You then called for those variables at lines 10 and 11 like so,
    $(".text").text(randomQuote);
    $(".author").text(randomAuthor);

So, those 2 variables were defined specifically within the scope of randQuote(), which means only randQuote() has access to it. You then tried to access those variables from the global environment, and they cannot be found. To fix this, initialize the variables before you call the function on lines 1 and 2 like this:

  var randomQuote;
  var randomAuthor;

This sets the values of those 2 variables to undefined, and you can change them at any point. Next, within randQuote() you will need to set the values of those 2 variables.

    randomQuote = text[num];
    randomAuthor = author[num];

Since those variables are defined globally any function can access and change them. This will give you access to the variables outside of randQuote().

  1. Last issue is with the onClick event on line 13. You are calling the function as you should, but since there was a mis-understanding with the scope of where your 2 variables from earlier lived, they aren’t getting called. They need to get called immediately after your function and not before the onClick event, so it would look like this:
  $("#next").on("click", function(){
    randQuote();
    $(".text").text(randomQuote);
    $(".author").text(randomAuthor);
  }); 

I forked your project so you can see that mine is working,
https://codepen.io/tsjohns9/pen/JMrpxY

Here is my random quote generator

Perfect, thank you so much! I really appreciate it, I’ll make sure to review scope.

Thank you so much, really appreciate it!

Got it working perfectly after, just have to add quotes and play around with the styling. Thank you very much, Randell.

I did offer insight into his original question by explaining where the issues where. The main issue was that there were variables being called out of scope.