Reputation: 5279
Let's say I have labels and I attach two click events to it:
$('#l1').bind('click',function(){
alert('label clicked');
}
$('#l2').bind('click',function(){
alert('label2 clicked');
}
$('#l3').bind('click',function(){
alert('label3 clicked');
}
$('label').bind('click',function(){
if($(this).hasClass('disabled')
return false
}
<label id='l1'>hi</label>
<label id='l2' class="disabled">bye</label>
<label id='l3'>hi</label>
Now I don't want the alert to be displayed when the label that has class disabled
is clicked.
Is it possible to do that?
Note : alert
is just a dummy thing.. I am performing a set of actions instead of that.. each different on basis of the actual label
Upvotes: 8
Views: 3878
Reputation: 150010
If multiple event handlers are bound to the same element for the same event the handlers are called in the order they were bound. If you call event.stopImmediatePropagation()
within a particular handler it will stop subsequent handlers being called.
So modify your $('label').bind()
as follows:
$('label').bind('click',function(event){
if($(this).hasClass('disabled') {
event.stopImmediatePropagation();
return false;
}
}
and move that up above your other .bind()
calls. Then that particular handler will execute first and have the chance to prevent the other handlers from executing.
(Note that .stopImmediatePropagation()
is not the same as .stopPropagation()
] - the latter stops the event bubbling up the DOM tree but doesn't stop other handlers on the same element.)
Upvotes: 22