Matt
Matt

Reputation: 26971

Preventing jQuery event triggering from sub elements

I have the following code:

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.6.2.min.js" 
    type="text/javascript">
    </script>
  </head>
  <body>
    <div id="a">
      <div id="b">
        <script type="text/javascript">
              $('#b').bind('fuffle',function() {alert('b fuffled');})
        </script>
        <div id="c"></div>
      </div>
    </div>
  </body>
</html>

When I run:

$("#b").trigger('fuffle')

I get the alert box as I would expect. However, when I run:

$("#c").trigger('fuffle')

I also get the alert box. I am guessing this because c is nested in b, however, is there a technique where this behavior could be avoided.

In my code, sub elements can also trigger fuffle, but they are bound to a different method. This behavior is literally causing a JS stackoverflow error.

Upvotes: 0

Views: 188

Answers (3)

Matt Ball
Matt Ball

Reputation: 359776

JavaScript events bubble up the DOM. You can either:

Upvotes: 2

Ilia Choly
Ilia Choly

Reputation: 18557

maybe have a simple check

$('#b').bind('fuffle',function(){
    if($(this).attr("id") == "b"){
        alert('b fuffled');
    }
});

Upvotes: 1

tomfumb
tomfumb

Reputation: 3759

Try passing the event to your anonymous handler function like

...'fuffle', function(e) {alert...

then call

e.stopPropagation()

which will prevent the event bubbling. The more blunt approach is to return false.

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

Upvotes: 3

Related Questions