Event Bubbling Vs. Event Capturing

Event bubbling and event capturing are two phases of the event propagation process in the DOM (Document Object Model) when an event occurs on an element within a web page. These mechanisms define the order in which event handlers are executed when an event is triggered on a nested structure of HTML elements. Understanding these phases is important for managing event handling and interactions in JavaScript.

Event Bubbling

Event bubbling is the default behavior in most browsers. When an event is triggered on an element, it starts at the target element and then bubbles up through its parent elements in the DOM hierarchy, one level at a time, until it reaches the root of the document (the window object).

run this source code Browser View
FORM
DIV

P

Click anywhere inside Div

Source
<form onclick="alert('Event from form')" style="border: 2px solid blue;width:200px ; ">FORM <div onclick="alert('Event from div')" style="border: 2px solid green;width:150px ; ">DIV <p onclick="alert('Event from p')" style="border: 2px solid red; width:100px; ">P</p> </div> </form>

Event Capturing (aka Trickling)

Event capturing is the opposite of bubbling. It's a less common behavior where the event starts from the root of the document and trickles down through the DOM hierarchy to the target element. However, it's important to note that not all browsers support event capturing by default.

document.getElementById("outer").addEventListener( "click", function() { console.log("Outer div clicked (capturing phase)"); }, true // The 'true' parameter enables event capturing ); document.getElementById("inner").addEventListener( "click", function() { console.log("Inner div clicked (capturing phase)"); }, true );

With the above code, if you click on the "Inner div," you'll see both event handler outputs in the console, but in the opposite order compared to event bubbling:

Outer div clicked (capturing phase) Inner div clicked (capturing phase)

Stopping Propagation

You can use the event.stopPropagation() method within an event handler to prevent further propagation in either the bubbling or capturing phase. This can be useful to stop an event from triggering other handlers in the propagation chain.

document.getElementById("inner").addEventListener("click", function(event) { console.log("Inner div clicked"); event.stopPropagation(); });

In this case, if you click on the "Inner div," only the handler for the "Inner div" will run.

Conclusion

Understanding event bubbling and capturing is crucial for controlling how events propagate through the DOM and for managing interactions within complex structures of HTML elements. It allows you to create more organized and efficient event handling in your web applications.