Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Interrupt animation?

I'm using jQuery for some simple animation effects once user clicks something. However, if they click again before the first animation has completed, nothing happens. They must wait until the first animation has finished.

Is there a way to interrupt the animation process and begin from scratch when a second click occurs?

Thanks.

like image 882
Dan Avatar asked Sep 15 '09 14:09

Dan


People also ask

How do you stop animation?

To remove more than one animation effect from text or an object, in the Animation Pane, press Ctrl, click each animation effect that you want to remove, and then press Delete. To remove all animation effects from text or an object, click the object that you want to stop animating.

Why is stop () method added before calling animate () in jQuery?

Why do we usually add the stop() method before calling animate() ? stop() halts the execution of the scripts on the page until the animation has finished. stop() ends any currently running animations on the element, and prevents conflicts and pile-ups. We tell jQuery that the animation has to be stopped at some point.

How do I stop a jQuery script?

The stop() method is an inbuilt method in jQuery which is used to stop the currently running animations for the selected element. Syntax: $(selector). stop(stopAll, goToEnd);


2 Answers

you could use the stop() method

HTML:

<input type="button" value="fade out" id="start">
<input type="button" value="stop" id="stop">
<div style="background-color: blue; height: 100px;">Testing</div>

JS:

$("#start").click(function() { $("div").fadeOut("slow"); });
$("#stop").click(function() { $("div").stop(); });

edit: The above code is tested and works in FF3.5 and IE8

Use that on the element that you would like to interrupt the animation of.

Just remember that the element will stop animating mid-animation. So you might need to reset the CSS after the stop, depending on your circumstances.

edit2: As of jQuery 1.7 there has been some updates. You can now group animation queues with names. So the stop() method will accept a boolean or a string as first parameter. If it's a boolean, it will clear/not clear all queues. But if you supply a string, then it will only clear the animations in that queue group.

like image 54
peirix Avatar answered Oct 03 '22 05:10

peirix


you can just stop() before relaunching the animation

$("#start").click(function() { $("div").stop().fadeOut("slow"); });
like image 39
pixeline Avatar answered Oct 03 '22 05:10

pixeline