35

How do I stop custom event bubbling in jQuery?

For example I have this code:

$('.myclass').bind('amodaldestroy', function(){
    ....does something.....
})

How do I only allow this to be triggered once on the first element it finds when bubbling? Can I just add return false?

$('.myclass').bind('amodaldestroy', function(){
     ....does something.....
    return false;
})
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Stann
  • 13,518
  • 19
  • 65
  • 73

5 Answers5

48

According to jQuery's documentation:

$('myclass').bind('amodaldestroy'), function(event) {
    ....does something....
    event.stopPropagation();
});
Daniel T.
  • 37,212
  • 36
  • 139
  • 206
13

Use event.stopPropagation();

$('.myclass').bind('amodaldestroy', function(e){
    e.stopPropagation();
});

You can also use return false but there is a subtle difference between the two in that returning false also calls event.preventDefault();

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
8

For support in IE < 9:

$(".element").click(function(e)
{
    var event = e || window.event;
    event.stopPropagation ? event.stopPropagation() : (event.cancelBubble=true);
});
David Sherret
  • 101,669
  • 28
  • 188
  • 178
5

This might not be that great but

return false;

return false will do both stopPropagation and event.preventDefault...

if you want only one you can choose based on your choice

please read this , this is from SO only

return false is effectively both preventDefault and stopPropogation.

preventDefault will prevent the default event from occuring, stopPropogation will prevent the event from bubbling up and return false will do both.

kobe
  • 15,671
  • 15
  • 64
  • 91
2

http://api.jquery.com/event.stopPropagation/

Codler
  • 10,951
  • 6
  • 52
  • 65