Event Bubbling

While going through a course on reactjs I suddenly remembered the concept of event bubbling back from the days of jquery. When an event occurs, it can trigger the handler on current control, plus handler in its parent.

Event bubbling occurs in the order from the target element to the root of the document.

Here is an example of the event bubbling. You can try running from jsfiddle link.


  <div id="parent">

<div id="child">Click me</div>
</div>

<script>
$(document).ready(function() {
$("#parent").on("click", function(event) {
alert("Parent div clicked!");
// Uncomment the next line to stop event bubbling
// event.stopPropagation();
});

$("#child").on("click", function(event) {
alert("Child div clicked!");
// Uncomment the next line to stop event bubbling
// event.stopPropagation();
});
});
</script>

When you run the script, you will first see “Child div clicked!” alert followed by “Parent div clicked!”.

If you dont want the event to reach parent, you can call event.stopPropagation() on the child event handler.

There is a dirth of information in this stackoverflow thread if you want to dig deeper.

Why Does This Model Exist?

Per W3C document, it is designed with two main goals.

Generic Event System

The first goal is the design of a generic event system which allows registration of event handlers, describes event flow through a tree structure, and provides basic contextual information for each event. More details in this W3C document.

Backward Compatibility

The second goal of the event model is to provide a common subset of the current event systems used in DOM Level 0 browsers. What is DOM Level 0? It doesn’t specifically denote a version of the DOM. Instead, it historically refers to the early days of JavaScript and web development when browsers implemented their own proprietary JavaScript features, and there wasn’t a standardized DOM.

Ending Note

There should always be a reason for any model to exist, be it DOM or the this event model. It will always help in understanding the scripting language better, because we understand the philosophy behind it.

Leave a comment