Prevent bubbling in javascript/jquery

Whenever an event on an element is triggered, it bubbles up through all its parents till it reaches the html element. i.e If we trigger a click event on element1 then all the click events of its parents will be triggered one by one.

bubbling

In the above diagram, elem1 click event triggers click event of elem1, then of elem2 and finally of elem3.
We can get which element’s event has caused bubbling by event.target
So, if we want to check for the actual base element whose event was triggered, then we can check for event.target in all elements click event which will always return elem1 in the above example.

To prevent bubbling we can use the following :
event.stopPropagation()
But for Internet Explorer version <9, you need to use
event.cancelBubble = true

So for cross-browser compatibility, you can use the below simple code snipplet:

$("#elem1).click(function(event) {
  // cross-browser event
  e = event || window.event;
  //browsers other than IE
  if (e.stopPropagation) {
      e.stopPropagation();
  } 
  else
  {
      // IE < 9
      e.cancelBubble = true;
  }
});

For any query, please feel free to ask/comment.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>