Reputation: 586
<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
function newQuote(){
var RandomNumber = Math.floor(Math.random())*Quotes.length;
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
</script>
</head>
<h5>
Simple Quote Generator
</h5>
<body>
<p id = "QuoteDisplay">
</p>
<button onclick="newQuote()">New Quote!</button>
</body>
</html>
This is a simple Quote Generator that I am building as a part of FreeCodeCamp. The aim is basically to generate a new Quote whenever the user clicks on the Buttton. However when I click on the button the text isn't getting displayed. What is wrong/missing in my code?
Upvotes: 0
Views: 115
Reputation: 17481
This is the working example with some fixes.
https://jsbin.com/meqetumini/edit?html,js,output
function newQuote(){
var RandomNumber = Math.floor(Math.random()*Quotes.length);
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
$('#new-quote-btn').click(newQuote)
Upvotes: 1
Reputation: 65883
You just need make sure that you have the JQuery library referenced BEFORE the script is encountered AND then to move a single parenthesis in this line:
var RandomNumber = Math.floor(Math.random())*Quotes.length;
So that it is:
var RandomNumber = Math.floor(Math.random()*Quotes.length);
By moving the closing parenthesis so that it comes AFTER Quotes.length
, you ensure that the random number that is generated (from 0 to 1) gets multiplied by the length of the array BEFORE getting rounded down. If you don't do this, the random number will always get rounded down to 0.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
function newQuote(){
var RandomNumber = Math.floor(Math.random()*Quotes.length);
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
</script>
</head>
<h5>
Simple Quote Generator
</h5>
<body>
<p id = "QuoteDisplay"></p>
<button onclick="newQuote()">New Quote!</button>
</body>
</html>
Upvotes: 3
Reputation: 11
Math.floor(Math.random()) always return 0 so anything you multiply it by will be 0
Upvotes: 1