Tricky javascript codes part 3



This content originally appeared on DEV Community and was authored by MD ASHRAF

  • We have 3 nested boxes (box1, box2, box3). When clicking each box, log its ID to the console. Clicking an inner box should NOT trigger clicks on outer boxes.

Image box

What is this question about?
This question is about event handling and event propagation in JavaScript, specifically how to control the flow of click events when you have nested HTML elements.

The core problem it addresses is how to prevent a click on an inner element from also triggering the click events of its parent (outer) elements. This is a common scenario in web development where you want specific actions to happen only when a particular element is clicked, and not its containers.

Solution: There are many ways to do the same but the more optimisez way is Wrapping all the divs inside one parent div having id as container.

Then adding event listener on this parent element

.html file:

<div id="container">
    <div id="box1" class="box">
      box1
      <div id="box2" class="box">
         box2
         <div id="box3" class="box">box3</div>
      </div>
    </div>
</div>

.css file

.box {
  min-width: 200px;
  width: fit-content; // to match width of div till its content
  border: 1px solid #000;
  padding: 15px;
}

#box1 {
  background-color: yellow;
  padding: 10px;
}
#box2 {
  background-color: cyan;
  padding: 10px;
}
#box3 {
  background-color: red;
}

script file.js

document.getElementById('container').addEventListener('click', event => {
  // Todo on click of container element or any of its child
  if (event.target.classList.contains('box')) {
    /* checking if click happens only on element having class as box, as we don't need to handle click for all other children of container as of now, instead of box.*/

    console.log('id is: ', event.target.id);
    event.stopPropagation(); // preventing event from propagation to parent on click of child element
  }
})

Live example here

IMPORTANT: As I have said earlier there can be many ways to solve this problem, we can add event listener to each individual divsalso, because only 3 divs are there for now, but if no. will be more then we will need loop etc.

So to avoid loop, we have taken parent element. we can take <body> also as a parent element, but then script will search to a wider aread of code and will be time consuming. Thus we have narrowed down the scope of event listener to a small area which is a div with id as container.

📌📌 More Javascript interview related code here:

Tricky Javascript code part2


This content originally appeared on DEV Community and was authored by MD ASHRAF