How to disable click event until animation is completed?
I want to disable the 'click' event until an animation is completed.
Mark Up
<ul>
<li data-name="item1" class="nav">Item 1</li>
<li data-name="item2" class="nav">Item 2</li>
</ul>
Here is my jQuery Code
$('.nav').live('click', function(){
$('.nav').unbind('click');
var itemId = $(this).data('name');
if( itemId === 'item1') {
$('#item1').animate({
'left' : '300'
}, 300, function(){
$('.nav').bind('click');
});
} else if( itemId === 'item2') {
$('#item2').animate({
'left' : '300'
}, 300, function(){
$('.nav').bind('click');
});
}
});
The above code doesn't seem to work. How do I fix it? [I开发者_Go百科f I click on 'Item 2' before 'Item 1's animation is completed, 'Item 2' also starts animating. I want to be able to animate only one at a time]
You could try this:
$(".nav").click(function(){
if ($('#item').is(':animated'))
{
return false;
}
...
});
Use .bind, because .live() binds to document.
$('.nav').bind('click', function(el, ev) {
clickme($(this), ev)
});
function clickme(obj, ev) {
obj.unbind(ev);
console.log(obj.css('margin-left'));
var dest = 0;
if (obj.css('margin-left') == '0px') {
dest = '300';
}
obj.animate({
'margin-left': dest
}, 3000, function() {
obj.click(function() {
clickme(obj)
})
workig sample: http://jsfiddle.net/oceog/CzkBu/
You could use the :animated selector to check if one of the element is animeted:
$('.nav').live('click', function(){
$('.nav').unbind('click');
var itemId = $(this).data('name');
var animated = $('.nav:animated').length;
if( itemId === 'item1' && animated === 0) {
$('#item1').animate({
'left' : '300'
}, 300, function(){
$('.nav').bind('click');
});
} else if( itemId === 'item2' && animated === 0) {
$('#item2').animate({
'left' : '300'
}, 300, function(){
$('.nav').bind('click');
});
}
});
you could set a boolean to false when the animation is playing, and set it to true when the animation is finished. In the click handler, if the boolean is true, do the stuff you want to do on the click.
This is my code for one of the project i needed. Point is to make some variable at the beginning ,set it to lets say 1, then on click u check if var is 1, if it is then proceed with animation, then in next line u set variable as 0 or anything else except 1, and again set it as 1 on callback function after animation ends. I needed fade in/out. BUt anyway, this is really simple method. Here is the code:
var available = 1;
$('a.contact').click(function(){
console.log(available);
if( available == 1) {
available = 0;
$('.red-arrow').fadeIn('slow', function(){
$(this).delay(2800).fadeOut('slow', function(){
available = 1;
});
});
}
})
精彩评论