jeff64 jeff64 - 3 months ago 11
jQuery Question

Getting a jQuery .click() to activate more than once

I am working on a quote machine that when clicked displays one of the random quotes and it's author found in my arrays. I can get it to display a random quote once, but clicking the button again does nothing.

The HTML

<div class="quote-box">
<h1>Random Quote Generator</h1>
<p class="quotes">This is where the quotes go.</p>
<span class="quote-authors">Quote author</span>

<div class="social-media">
<a href="#"><i class="fa fa-twitter"></i></a>
<a href="#"><i class="fa fa-tumblr"></i></a>
</div>

<button class="quote-button">New Quote</button>
</div>


The Javascript

//VARIABLES
///////////////
var quotes = [["Quote 1", "Author 1"], ["Quote 2", "Author 2"], ["Quote 3", "Author 3"], ["Quote 4", "Author 4"]];

var randomQuote = quotes[Math.floor(Math.random() * quotes.length )];


//FUNCTIONS
///////////////
function quoteGeneration() {
$(".quotes").replaceWith(randomQuote);
};


//QUOTE BUTTON
/////////////////
$(".quote-button").click( function() {
quoteGeneration();
});

Answer

There are two main issues. The first is because you remove the .quotes element from the DOM on the first click. Use text() instead of replaceWith():

$(".quotes").text(randomQuote);

The second is that your logic is flawed as you only pick a quote randomly once on load of the page. That should be done within the click handler. Try this:

var quotes = [
  ["Quote 1", "Author 1"],
  ["Quote 2", "Author 2"],
  ["Quote 3", "Author 3"],
  ["Quote 4", "Author 4"]
];

$(".quote-button").click(function() {
  var randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
  $(".quotes").text(randomQuote);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="quote-box">
  <h1>Random Quote Generator</h1>
  <p class="quotes">This is where the quotes go.</p>
  <span class="quote-authors">Quote author</span>

  <div class="social-media">
    <a href="#"><i class="fa fa-twitter"></i></a>
    <a href="#"><i class="fa fa-tumblr"></i></a>
  </div>

  <button class="quote-button">New Quote</button>
</div>

Comments