JQuery slideToggle() clicked multiple times - prevent animation
Asked Answered
R

3

12

I've searched around for a solution for a while, but can't seem to find it. I thought maybe using JQuery's .clearQueue() as in my fiddle, but it doe'snt work.

Here's the fiddle.

To be clear: I want the sideToggle() to execute, but as soon as it gets clicked again & the first slideToggle() hasn't finished yet, it should stop the animation of the first and slide back up. Using the .clearQueue() method it does work for two clicks, but when clicked eg three times, the box dissapears and the heigt is somehow messed up.

Renoir answered 26/1, 2013 at 17:18 Comment(3)
You could use jquery.stop() api.jquery.com/stopHeadwind
Thanks mate! Learning new jquery stuff every day! :)Renoir
use jquery .stop function like this : $('div').stop().slideToggle();Bohs
R
22

Using the jquery .stop() api does the trick.

Working example.

Renoir answered 26/1, 2013 at 17:32 Comment(1)
Using stop() during the animation can lead to bad situations where the original height cannot be reached anymore. See @Hacktisch answer for solutionAho
E
6

Using stop() during the animation can lead to bad situations where the original height cannot be reached anymore.

Another option is to force the animation to finish before the click can fire it again:

function clickFunc() {
    var $this=$(this);
    if($this.hasClass('toggling')){return;}
    $this.addClass('toggling')
    $this.stop().slideToggle(300,function(){
        $this.removeClass('toggling');
    });
}
Esta answered 24/7, 2015 at 14:13 Comment(0)
M
3

There is a plugin that you could probably make use of for halting and resuming animations that is not native to jQuery: http://tobia.github.com/Pause/

If you don't need your animations to be that finely tuned, then you can use .finish (added jQuery 1.9) instead of .clearQueue. Problem is that that finishes the animation suddenly, which looks a little weird.

Problem is that jQuery doesn't keep track of whatever the original height of (just put $("div").data('originalHeight', $("div").height()) to do this yourself). That will prevent the height from getting screwed up by clearining the queue in the middle of the animation:

http://jsfiddle.net/xj3Py/3/

This is still not perfect since it jumps around with 3 or more clicks, but at least the height doesn't screw up.

Meanie answered 26/1, 2013 at 17:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.