JQuery... Why does this sometimes run twice or more?

JQuery... Why does this sometimes run twice or more?
0.0 0

#1

Hello! I have this bit of code set up for my pretty neat quote generator challenge project:

    $("button").click(function() {
      $(".theQuote").slideUp("slow", function() {
        $.getJSON("https://talaikis.com/api/quotes/random/", function(chosenQuote) {
          $(".quote").text(chosenQuote.quote);
          $(".author").text(chosenQuote.author);
        });
      })
      .delay(500);
      $(".theQuote").slideDown("slow");
    });

It’s meant to:

  1. Operate on the click of the button
  2. Slide the div up, hiding the old quote
  3. Get the random quote API I chose
  4. Insert the new quote in the old quote’s place
  5. Slide the div down, revealing the new quote

It works! But whenever I click the button, sometimes it runs twice, or three times. It does the whole thing, sliding up, changing the quote, and sliding back down. Does anyone see the reason why this is? I’m a little baffled.


#2

Try to set your listener this way:
$(“button”).click(function(e) {
e.stopPropagation();
//The rest of your code here
});


#3

This seems to have solved it. I think I’ll go read and learn what that even means! :stuck_out_tongue:

Edit: Actually, it seems to still have the intermittent issue of running twice. It didn’t seem to at first, so I thought it was fixed! Whoops.


#4

Hmm, maybe you’re somehow binding the listener twice. Are you coding this on codepen? If so, can you share the link?


#5

Dag nabbit. I’m using atom.

However, I think what’s happening is my impatient self is clicking twice before it finishes sliding down. So, I added a simple stop() in there and it seems to be doing the trick! It stops it right after I click, and then just goes on to the next quote!


#6

Ah, awesome! Glad you figured it out :slight_smile: