How can I temporarily disable click events on a button without actually disabling it?
Not hard to do since jQuery already stores all of its event handlers as data()
on the element itself. You can get (and modify) this object through .data().events
.
Now you can easily save a reference to the handlers with:
events._click = events.click;
events.click = null;
And then restore them by using:
events.click = events._click;
events._click = null;
Note that this won't disable events that are bound via .delegate()
or .live()
, as they work by event bubbling/propagation. To disable those as well, simply bind a new handler that blocks propagation to ancestor elements:
events._click = events.click;
events.click = null;
// Block .live() and .delegate()
$("#el").click(function (e) {
e.stopPropagation();
});
You don't even need to unbind this blocker function when it's time to enable the handlers again, since events.click = events._click
will override the function you just bound with all the old handlers.
Here is yet another way:
$("#myButton").click(function() {
if ($(this).attr("temp_disable") == "disabled") {
//nothing to do, temporarily disabled...
}
else {
alert("You clicked me!");
}
});
To "disable" it for 10 seconds:
$("#myButton").attr("temp_disable", "disabled");
window.setTimeout(function() { $("#myButton").attr("temp_disable", ""); }, 10000);
Live test case: http://jsfiddle.net/yahavbr/ByM6h/
That is the way to go. If you have onclick specified as an attribute you may switch the attribute busing
$(button_element).attr('click', '');
and
$(button_element).attr('click', 'do_the_regular_action()');