"Disable" a link temporarily when clicked?
I have a link that when clicked, performs some animation functions to some divs etc and works very well. My problem is when I click the button more than once etc, the animation looks weird. I would like it so, that when my button is cl开发者_开发百科icked, the button is "disabled" for say 2 seconds.
I don't think I need to post the code, but just ask if you think you need it.
My link is like so:
<a href="button">Click</a>
Yes, you can absolutely do this.
You add a click handler and use preventDefault()
when the animation is running until it is complete. More about preventDefault is in the jQuery docs. You can use a flag or change your click handler after the first click to accomplish this. Here's an example with a flag.
var isAnimating = false;
$("#animationLink").click(function(e) {
if(!isAnimating) {
isAnimating = true;
setTimeout("isAnimating = false", 2000); // set to false in 2 seconds
// alternatively you could wait until your animation is done
// call animation code
} else {
e.preventDefault();
}
});
return false;
from your click handler will have the same effect as preventDefault with the added action of preventing event bubbling up the DOM.
Here's a self-contained way to do it using one
, which automatically unbinds the click handler after a single trigger, and a click function that rebinds itself:
$('#yourlink').one('click', function clicker(){ // name the function
var that = this;
event.preventDefault();
do_your_stuff_here();
var rebind = setTimeout(function() {
$(that).one('click',clicker); // ...then rebind by name
}, 2000);
});
Here's a working example: http://jsfiddle.net/redler/8sGqK/
If you don't want the link to work when you click it, you need to return false.
$('a').click(function(){
if (doSomeCheck()) {
//run animation
} else {
return false; //don't want the link to work
}
});
However, I recommend you look at the effects API and the .stop()
method to fix your animation getting wonky : http://api.jquery.com/category/effects/
Without using global variables or timeOuts you could leverage the callback for your animation to reassign the function.
function DoTheAnimation(){
var $a = $(this);
var h = $("div").height() + 100;
$("div").animate({'height': h}, "slow",function(){
$a.one("click.animate", DoTheAnimation);
});
}
$("a").click(function(event){event.preventDefault();}).one("click.animate", DoTheAnimation);
Code example on jsfiddle.
精彩评论