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)?
Here is what you can do:
First, bind an event handler to the
.disabledelements which prevents other handlers to be executed and prevents the default action: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
disabledelements will always execute first and prevent other handlers from executing (throughstopImmediatePropagation[docs]).DEMO