Reputation: 10552
I know there is a way to stop the code from looping everytime you call an animation in jquery but for the life of me i can not find it!
How can i turn this code below in order for it not to keep looping if i push the button more than one?
$('#message-box').slideDown('slow').delay(10000).slideUp('slow');
If i hit the button that calls that more than once then it slides down, displays for 10 secs, slides back up then back down again.
What i would like it to do is if its already down and i hit the button then NOT to display it again. Or if nothing else, slide up the current message and slide down the new one right then and there without the delay between.
Any help would be great!
David
Upvotes: 0
Views: 626
Reputation: 8930
Using .stop() is the obvious answer but when used with .slideUp() a small fraction of height is still displayed whenever .stop() is invoked. You could use .stop(true,true) but that will cause the slide animation to 'jumptoend' causing jerky animation. Not ideal.
Consider using .animate()
instead of .slideUp()
$('button').click(function() {
$('#message-box').stop(true).animate({height: 100}).delay(1000).animate({height: 0});
});
Upvotes: 0
Reputation: 491
This will check to see if the message element is already being animated before running the function.
$('#btn').click(function () {
if (!$('#message-box').is(':animated')) {
$('#message-box').slideDown('slow').delay(10000).slideUp('slow')
}
});
Upvotes: 2
Reputation: 150080
You could try this:
$('#message-box').stop(true,true).slideDown('slow').delay(10000).slideUp('slow');
If there is a down-delay-up animation already in progress for the element then .stop(true)
will stop that, clear the element's animation queue, and only then requeue the down-delay-up thing.
Demo: http://jsfiddle.net/bSeE7/
Upvotes: 1
Reputation: 5205
You need a conditional to prevent it from being activated when it's running. The callback function will reset the boolean to allow you to then click on it again when the animation is finished.
var animationRunning = false;
if(!animationRunning) {
$('#message-box').slideDown('slow')
.delay(10000)
.slideUp('slow', function() { animationRunning = false; });
animationRunning = true;
}
Upvotes: 1
Reputation: 3290
$('#message-box').slideDown('slow', function(){
$('#message-box').delay(10000).slideUp('slow');
})
Upvotes: 1
Reputation: 171698
Simplest method if you only want event to occur once is one()
$('#myButton').one('click', function(){
$('#message-box').slideDown('slow').delay(10000).slideUp('slow');
})
Upvotes: 1