Event Bubbling and Stop Propagation
Learn about event bubbling and how to restrict it using stop propagation.
We'll cover the following
What is event bubbling?
Event bubbling or event propagation is an important concept in JavaScript and jQuery. To understand this concept, let’s examine the example below.
The following HTML page has three nested elements. A span
element is nested within a paragraph
element, and the paragraph
element is further nested within a div
element. This nesting can be visualized in the page output. In the JavaScript for this web page, we use jQuery to set up click
event handlers for all three elements. Each event handler, once triggered, displays an alert box with the text specifying the clicked element (div
, p
, or span
).
Now let’s click on the span
element. It displays the expected alert box with the text “Span is clicked.” However, as soon as we press ok, another alert box appears with the text “paragraph is clicked”. This is followed by the third alert box with the text “Div is clicked.” So, what has happened?
When the span element is clicked, its click event handler is triggered. That span element then bubbles up the DOM tree, triggering each of its parents click event handlers down to the document root.
This bubbling or propagation of events down the DOM tree is known as event bubbling or event propagation in jQuery.
Can you guess what would happen if we removed the click handler from the paragraph element? Go ahead and try it!
Stop Propagation
What if we want to stop this bubbling and propagation of events? What if we want to trigger just the span
click event handler, in the example above and not the parent click event handlers? This is where eventObj.stopPropgation()
comes into play.
The event object is passed as an argument to the event handler function. We call the event object’s method stopPropagation()
inside the event handler function in order to prevent the event from bubbling and propagating down the DOM tree.
For example, in the code above, we added the line eventObj.stopPropagation();
in all three click event handlers. Now, when we click the span
element, only one alert box is generated and it includes the text “Span is clicked.” The event is prevented from bubbling up and the parent click event handlers are not triggered.
Can you guess what would happen if we removed the call to
stopPropagation()
from the event handler for the paragraph element? Go ahead and try it!