Random quote machine help?

Random quote machine help?
0.0 0

#1

Hi everyone, I’m having a go at the Random Quote Machine challenge and I would like some help.

Here is the code I am using to generate a random quote from an array:

var quotesArray = ["one", "two", "three", "four", "five", "six", "seven"];

var randomNumber = Math.floor(Math.random() * quotesArray.length);

var randomQuote = quotesArray[randomNumber];

console.log(randomQuote);

The above code works as I want it to. My problem is that I don’t know how to use jQuery to insert my randomQuote variable in my html. I would appreciate any help with this, I’m currently trying to relearn jQuery as I clearly don’t have a great grasp on it


#2

Assuming you have an HTML element with an id of “quote”, it would be something like this:
$("#quote").html(randomQuote);


#3

Ok thanks! So my JS code currently looks like this. The issue is that it will generate a random quote on the first button click. But not again after that. What is the issue?

var quotesArray = ["one", "two", "three", "four", "five", "six", "seven"];

var randomNumber = Math.floor(Math.random() * quotesArray.length);

var randomQuote = quotesArray[randomNumber];

console.log(randomQuote);

$(document).ready(function(){
    $("button").click(function(){
        $("#quote").html(randomQuote)
        
    });    
    });

#4

randomQuote is a global variable. Move it inside the function.


#5

Thanks again for the help! I got it working :grin:


$(document).ready(function(){
    $("button").click(function(){
        var quotesArray = ["one", "two", "three", "four", "five", "six", "seven"];
        var randomNumber = Math.floor(Math.random() * quotesArray.length);
        var randomQuote = quotesArray[randomNumber];
        $("#quote").html(randomQuote);
        
    });    
    });