spaceDog spaceDog - 2 years ago 115
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>
<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">

<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>

<script src=""></script>
<script type="text/javascript" src="app.js"></script>

var randomQuotes = [
"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);


$("#clearButton").on('click', function(){


#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 Source

You need to make the following changes to your javascript:

var randomQuotes = [
    "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);

$("#clearButton").on('click', function() {

-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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download