Search code examples
javascriptjquerydomonclickevent-bubbling

A way to remove click events for element


I have an element #foo and it has click event on it. Element #foo is in element #bar which also has click event on it.

<div id="bar">
  <div id="foo" />
</div>

When #foo is clicked, #bar event gets called and #foo event gets ignored. That's now what I want.

I'm looking for a way to remove all click events from #foo element except my just set event and all events that are on parents for #foo.

Edit: Here is jsFiddle demo. I want 2nd event to get called before 1st event.

Edit #2: Here is my code with your suggestions. Doesn't work.


Solution

  • If you have a click event on foo and you dont want it to bubble you could do the following:

    $("#foo").on('click', function(e){
         e.preventDefault();
         e.stopPropagation(); //this line will stop the click bubbling up the tree.
    });