[JQuery] Event Propagation – Bubbling

Event propagation is confusing. Events can be propagated from top to down (capturing model) or from bottom to top (bubbling model). jQuery supports event bubbling. When an event is fired on a child element, it will get propagated to its parents.     

 

1. Event Bubbling

Let’s see the following HTML.

<div id="div1">
  Hello, World!
  <input type="button" id="btn1" value="Click Me" />
</div>

The button is inside the “div” element. If you add handers to the “click” event of both the button and the “div“, what will happen?

$(document).ready(function () {
  $('#btn1').click(function () {
    alert('Button is clicked');
  });
  $('#div1').click(function () {
    alert('Div is clicked');
  });
});

The result will be surprising to you.

If you click the button, you will see 2 message boxes (button -> div). If you click the “Hello, World” text, only one message box will pop up.

The example shows you how events are bubbling up to parent elements.

 

2. Checking the target

In many cases, bubbling is not what you want. You do not want to execute multiple handlers. The first solution to solve this problem is to check which element is clicked. Event handler can have an argument and its “target” property refers to most specific element in which an event is triggered.

You can compare the “target” property to “this” to determine if the event from the bubbling.

$(document).ready(function () {
  $('#btn1').click(function () {
    alert('Button is clicked');
  });
  $('#div1').click(function (e) {
    if (e.target == this) alert('Div is clicked');
  });
});

 

3. Stopping the bubbling

Checking the “target” property is not the best solution to stop the propagation, especially when the nesting of elements is quite complicated. The better way is to use stopPropagation()‘ method.

$(document).ready(function () {
  $('#btn1').click(function (e) {
    alert('Button is clicked');
    e.stopPropagation();
  });
  $('#div1').click(function () {
    alert('Div is clicked');
  });
});

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