JQuery Multiple event handlers - how to undo?

I have two functions related to the click event two different times (using jQuery). The order of their dismissal is significant. They shoot in the correct order. The problem is that when the first function returns false, the second function still fires!

How can I cancel the event correctly?

Code example:

$(document).click(function() { alert('a'); return false; }); $(document).click(function() { alert('b'); }); 

When you click on a page, you will still see a warning message "b". This is unacceptable!

+42
jquery javascript-events event-handling
Mar 16 '09 at 23:13
source share
5 answers

Use the stopImmediatePropagation function of the jQuery event object.

Saves the execution of other handlers. This method also stops the bubbles by calling event.stopPropagation ().

 $(document).click(function(event) { alert('a'); event.stopImmediatePropagation(); return false; }); $(document).click(function() { alert('b'); }); 
+81
Mar 16 '09 at 23:31
source share

First of all, I ask: why do you have two functions associated with the same click event? With access to the code, why don't you just make one single call?

 $(function (){ var callbackOne = function(e){ alert("I'm the first callback... Warning, I might return false!"); return false; }; var callbackTwo = function(e){ alert("I'm the second callback"); }; $(document).click(function (e){ if(callbackOne(e)){ callbackTwo(e); } }); }); 
+2
Mar 16 '09 at 23:28
source share

Thanks, unbind works to redefine functions.

  $(document).ready(function(){ $("#buscar_mercaderia").click(function(){ alert('Seleccione Tipo de mercaderia'); }); $(".tipo").live('click',function(){ if($(this).attr('checked')!=''){ if($(this).val()=='libro'){ $("#buscar_mercaderia").unbind('click'); $("#buscar_mercaderia").click(function(){ window.open('buscar_libro.php','Buscar Libros', 'width=800,height=500'); }); }else if($(this).val()=='otra'){ $("#buscar_mercaderia").unbind('click'); $("#buscar_mercaderia").click(function(){ window.open('buscar_mercaderia.php','Buscar Mercaderias', 'width=800,height=500'); }); } } }) 
+2
Mar 04 '11 at 18:41
source share

Does unbind use help?

 $(document).click(function() { alert('a'); $(this).unbind('click'); return false; }); 
+1
Mar 16 '09 at 23:16
source share

If which nickname said it doesn’t work, you can use a small state machine:

 var trigger = 0; $(document).click(function() { alert('a'); if(you_want_to_return_false) { trigger = 1; return false; } }); $(document).click(function() { if(trigger !== 0) { alert('b'); } trigger = 0; }); 

Not the nicest solution, but it will work.

0
Mar 16 '09 at 23:19
source share



All Articles