[JavaScript] Stopping Event Propagation

When you attach handlers to the nested elements, all handlers will be triggered. This is usually not what you want. Let’s find out how to stop the event propagation.

1. window.event.cancelBubble

In the legacy IE model, you can set the event’s “cancelBubble” property to true in order to turn the bubbling off.

function onClick1() {
  alert("1");
  window.event.cancelBubble = true;
}

This code works only in IE.

 

2. stopPropagation()

The recommended way to cancel the bubbling is to use the event’s “stopPropagation()” method.

document.getElementById("clickBtn1").onclick = onClick1;

function onClick1(e) {
  alert("1");
  e.stopPropagation();
}

 

3. jQuery

IE 7 and 8 does not support the “stopPropagation()” method.

jQuery’s event object is a wrapper object and provides the browser-consistent properties and methods.

$(document).ready(function () {
  $("#clickBtn1").click(onClick1);
});

function onClick1(e) {
  alert("1");
  e.stopPropagation();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s