jQuery Event Bubbling

There are two types of events. One is capturing model in which events can be propagated from top to down and the second one is Bubbling Model in which events can be propagated from bottom to top. JQuery supports Event bubbling. When an event is fired

on a child element, it will get propagated to its parents. In this post I will discuss Event Bubbling.

Event Bubbling
Let’s see the following HTML.

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

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

	$(document).ready(function () {
	 $("#btn_inner").click(function () {
	 alert("Button is clicked");
	 });
	 $("#outer_div").click(function () {
	 alert("Div is clicked");
	 });
	});

If you click the button, you will see 2 alert boxes (button -> div). If you click the “Hello, World” text, only one alert box will pop up.
The example shows you how events are bubbling up to parent elements.

Don”t want event bubbling use Target

In many cases, bubbling is not what you want. You do not want to execute multiple handlers. The first solution to In December love cancer monthly horoscope anticipate the most amazing romantic nbso stories. 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.

	$(document).ready(function () {
	 $("#btn_inner").click(function () {
	 alert("Button is clicked");
	 });
	 $("#outer_div").click(function (e) {
	 if (e.target == this) alert("Div is clicked");
	 });
	});

Best Solution to avoid Bubbling

Using 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 () {
	 $("#btn_inner").click(function (e) {
	 alert("Button is clicked");
	 e.stopPropagation();
	 });
	 $("#outer_div").click(function () {
	 alert("Div is clicked");
	 });
	});

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Skip to toolbar