Reputation: 5743
I'm using jquery and creating event handlers like this:
$('#some_selector a.add').live('click', function(){...});
However, I need to not execute handlers when an element has disabled
class. Then I wrote the following to achieve this:
$('#some_selector a.add:not(.disabled)').live('click', function(){...});
But I'm tired of watching over all the places that I need to add :not(.disabled)
, sometimes I forget to add it and so on. Moreover, if I have an anchor element and my handler prevents default action on it, than adding :not(.disabled)
will cause browser to open next page instead of doing nothing.
So is there a way to set up automatic disabling on handler execution when an element meets some condition (like having "disabled" class)?
Upvotes: 0
Views: 1640
Reputation: 816374
Here is what you can do:
First, bind an event handler to the .disabled
elements which prevents other handlers to be executed and prevents the default action:
$('#some_selector a.add.disabled').live('click', function(event){
event.stopImmediatePropagation();
event.preventDefault();
});
Then you can bind your other event handlers as you did before. As event handlers are executed in the order they have been bound, the event handler for disabled
elements will always execute first and prevent other handlers from executing (through stopImmediatePropagation
[docs]).
Upvotes: 2
Reputation: 434645
You could use <button>
instead of <a>
for this. A <button>
with the disabled
attribute set will not respond to clicks at all:
A form control that is disabled must prevent any
click
events that are queued on the user interaction task source from being dispatched on the element.
For example: http://jsfiddle.net/ambiguous/sCv8n/
You can style a <button>
to look pretty much any way you want too.
Upvotes: 2