WebGuy7767
WebGuy7767

Reputation: 67

How to prevent jQuery "fadeToggle" from looping over and over again?

I have a relatively simple question about jQuery (please forgive that I am a noob). I have used the "fadeToggle" (click) function on a div to display another element, however if the user clicks the div say 100 times, how do I stop the animation from playing over and over and over again for each click?

Upvotes: 0

Views: 812

Answers (4)

Marcus Stefansson
Marcus Stefansson

Reputation: 1

The easiest way is to use .(stop) example:

<div id="hover_on_me_box>Hover on me!</div>

<div style="display:none" id="hidden_box">Content....</div>

$("#hover_on_me_box").hover(function() {
    $("#hidden_box").stop().fadeToggle("500");
});

Read more here: http://www.learningjquery.com/2009/01/quick-tip-prevent-animation-queue-buildup

Upvotes: 0

Andrew
Andrew

Reputation: 13853

You can also verify the queue is empty before calling it,

$("button").click(function() {
    if (!$animatedElement.queue().length) {
      $animatedElement.fadeToggle("slow", "linear");
    }
});​

http://jsfiddle.net/EU5WK/

Upvotes: 2

Heitor Chang
Heitor Chang

Reputation: 6057

I've seen a variation of this question where a is running? kind of variable is used:

http://jsfiddle.net/VRDP9/

running = false;

$("button:first").click(function() {
    if (!running) {
      running = true;
      $("p:first").fadeToggle("slow", "linear", function() { running = false; });
    }
});​

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

You need to set some sort of indicator that you activate in the first iteration, then check for it at the beginning of that function. This can be a variable, or you can add and check for a class name on the target element.

Upvotes: 0

Related Questions