Why you should understand Event Bubbling and Capturing Phase in Html?

Event bubbling

<div id="outerDiv">
<div id="innerDiv">Inner div</div>
</div>
const outerDivElement = document.getElementById("outerDiv");

outerDivElement.addEventListener("click", function() {
console.log("outer div got clicked");
});
const outerDivElement = document.getElementById("outerDiv");
const innerDivElement = document.getElementById("innerDiv");

outerDivElement.addEventListener("click", function() {
console.log("outer div got clicked");
});
innerDivElement.addEventListener("click", function() {
console.log("inner div got clicked");
});

Event Capturing:

Explanation of Technical aspects:

Event Phases

  1. The capture phase: the event is dispatched to the target’s ancestors from the root of the tree to the direct parent of the target node.
  2. The target phase: the event is dispatched to the target node.
  3. The bubbling phase: the event is dispatched to the target’s ancestors from the direct parent of the target node to the root of the tree.

Summary of the above information:

  1. Name of an event.
  2. The callback function to run some code when the specified event is triggered.
  3. Optional: the Boolean value of capture. (Set to false by default).

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why do we use Middlewares ?

Understanding UTF in Javascript

StateTrak

Bitwise JavaScript Operators

3 Fundamental Concepts To Master Any Frontend Framework

404 Not Found with Docker, React Router and Nginx

Let us know about KoaJS

SerpApi’s returned `search_metadata` field and to make sense of it all

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Till Engineering

Till Engineering

More from Medium

GatePlay — A platform with much more than just entertainment

Planter’s Diary: Costa Rican Vs Guatemalan Vs Colombian

A young multi-stem Robusta Coffee patch on a South Indian plantation

CS373 Spring 2022: Nisha Ramesh

Getting Rid of Stuff & More Updates for 2022