Reputation: 241
<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
Reputation: 385144
There are two approaches here, subtly different from one another.
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).
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.
Upvotes: 1
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>
Upvotes: 1
Reputation: 5905
If ($("#myID").not(":animated"))
{
$('#myID').fadeToggle('slow');
}
Upvotes: 3
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
Reputation: 2810
This works in my testing:
$('.fade').click(function() {
$('#myID').stop(true, true).fadeToggle('slow');
});
The idea to add paramaters to stop()
came from this post: jQuery fadeToggle if currently animated, ignore further input
Upvotes: 0
Reputation: 37506
function fade() {
var that = this;
if (!$(this).attr('fading')) {
$(this).attr('fading', true);
$('#myID').fadeToggle('slow', function() {
$(that).removeAttr('fading');
});
}
}
Upvotes: 0