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
stopPropagation() method is an inbuilt method in jQuery which is used to stop the windows propagation.
The event. stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed. Tip: Use the event. isPropagationStopped() method to check whether this method was called for the event.
jQuery unbind() MethodUse the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.
stopImmediatePropagation() is an inbuilt method in jQuery used to stop the rest of the event handlers from being executed for the selected element. Syntax: event.stopImmediatePropagation()
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With