Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery stop calling other handler

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

like image 535
Gaurav Shah Avatar asked Nov 29 '11 11:11

Gaurav Shah


People also ask

How to stop other events in jQuery?

stopPropagation() method is an inbuilt method in jQuery which is used to stop the windows propagation.

How to stop Propagation in jQuery?

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.

How to unbind event jQuery?

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.

What is stopImmediatePropagation in jQuery?

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()


1 Answers

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.)

like image 167
nnnnnn Avatar answered Sep 30 '22 18:09

nnnnnn