Daniel
Daniel

Reputation: 241

Ignore if it's already fading

<p onclick="fade()">Click me</p>
<p id="myID">Text</p>

<script>
function fade() {
    $('#myID').fadeToggle('slow');  
}
</script>

If I spam "Click me", I mean if I click fast say ten times, "Text" continues to fade in and out until it has finished my ten clicks.

Is there anything I can do so that it ignores a click if it's already fading?

Upvotes: 1

Views: 224

Answers (6)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

There are two approaches here, subtly different from one another.


Approach 1

function fade() {
    var $obj = $('#myID');
    if (!$obj.is(':animated')) {
        $obj.fadeToggle('slow');
    }
}

This is what you asked for. A new fade will only be queued if one isn't already going on.

The downside here is that we check for any animation (not just toggle fades), but you could expand this if really necessary (e.g. see Mike Thomsen's answer).

Live demo.


Approach 2

Instead of blocking new fades, you could cancel the current ones:

function fade() {
    $('#myID').stop(true, true).fadeToggle('slow');
}

The downside here is that the new animation starts immediately and this looks rather jarring.

The second parameter to .stop must be true (or you'll lose the element's original full opacity forever), and flipping the first one does not fix the downside of this approach.

Live demo.

Upvotes: 1

Samuel
Samuel

Reputation: 1389

source: jQuery animation: Ignore double click

<p onclick="fade()">Click me</p>
<p id="myID">Text</p>

<script>
function fade() {
    if( !$('#myID').is(':animated') ) {
    $('#myID').fadeToggle('slow');  
    }
}
</script>

jsfiddle

Upvotes: 1

Liam Bailey
Liam Bailey

Reputation: 5905

If ($("#myID").not(":animated"))
{
 $('#myID').fadeToggle('slow');  
}

Upvotes: 3

Senko Rašić
Senko Rašić

Reputation: 421

Use http://api.jquery.com/queue/ to find out whether there are any effects being performed on the element already. Something like (not tested):

if ($('#myID').queue().length == 0) $('#myID').fadeToggle('slow');

If you do want to stop the current effect and perform the toggle, use .stop() instead.

Upvotes: 1

g_thom
g_thom

Reputation: 2810

This works in my testing:

$('.fade').click(function() {
    $('#myID').stop(true, true).fadeToggle('slow');

});

See jsfiddle

The idea to add paramaters to stop() came from this post: jQuery fadeToggle if currently animated, ignore further input

Upvotes: 0

Mike Thomsen
Mike Thomsen

Reputation: 37506

function fade() {
    var that = this;
    if (!$(this).attr('fading')) {
        $(this).attr('fading', true);
        $('#myID').fadeToggle('slow', function() {
            $(that).removeAttr('fading');
        });
    }
}

Upvotes: 0

Related Questions