spaceDog spaceDog - 5 months ago 20
jQuery Question

Javascript and Jquery Quotes generator

Hey I am trying to generate a random quotes using Javascript and Jquery.
Can someone tell me why it isn't working? I wrote a random generate function inside the document.ready and using it to generate random array index, but it is not out putting any quotes. Please help

<!DOCTYPE html>
<html>
<head>
<title>Random Quotes</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="box">
<p id="quotesBox"></p>
<button type="button" id="quoteButton" class="buttons" class="btn btn-primary">Give me a Quote</button>
<button type="button" id="clearButton" class="buttons" class="btn btn-primary">Clear</button>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>


$(document).ready(function(){
var randomQuotes = [
"Doh",
"Mom, where's my meatloaf",
"This is spartan",
"Stay here,I will be back ",
"You talking to me? You talking to me??"
];


$("#quoteButton").on('click', function(){
function randomQuotes() {
return Math.floor(Math.random() * randomQuotes.length);
}

$("#quotesBox").text(randomQuotes[randomQuotes()]);
});


$("#clearButton").on('click', function(){
$("#quotesBox").text("");
});

});


#box {
height: 500px;
width: 500px;
background: rgb(205, 255, 255);
margin: 0 auto;
}


.buttons {
position: 0px 0px 0px 70px;
margin: 100px -130px 0px 150px;
border: 2px solid;
border-radius: 25px;
color: #FF00FF;
background: white;
}

#quotesBox {
font-weight: 600;
text-align: center;
padding-top: 150px;
}

Answer

You need to make the following changes to your javascript:

http://codepen.io/anon/pen/GqpBzj

var randomQuotes = [
    "doh",
    "Mom, where's my meatloaf",
    "This is spartan",
    "Stay here,I will be back ",
    "You talking to me? You talking to me??"
];

$("#quoteButton").on('click', function() {
  var x = Math.floor(Math.random() * randomQuotes.length);
  $("#quotesBox").text(randomQuotes[x]);
});

$("#clearButton").on('click', function() {
  $("#quotesBox").text("");
});

-Reasons For Changes-

1) You don't need the $(document).ready(function(){}); if you are simply adding event handlers

2) Refrain from defining functions within other functions when it is not necessary. You can simplify that by just passing the Math.floor(...) to a variable.

3) Don't be afraid to write things out. No reason to mega-condense things all into one line.

4) Keep function/variable names unique or more descriptive. It is confusing for other users when they see an array and a function with very similar names.

Comments