JS Problems geeksforgeeks Exercises and Solutions for Beginners

How to Listen for Only Parent Events (Not Children) in JavaScript 📌[All Method]️

The blog is about How to Listen for Only Parent Events (Not Children) in JavaScript & provides a lot of information to the novice user and the more seasoned user. After completing this guide, you will know how to face these kind problem.
Question: What is the best solution for this problem? Answer: This blog code can help you solve errors How to Listen for Only Parent Events (Not Children) in JavaScript. Question: What is causing this error and what can be done to fix it? Answer: Check out this blog for a solution to your problem.

I was writing out a component in React that required an overlay with some buttons on it, so I needed a way to differentiate parent element and child element events.

The overlay was the parent element and each button was a child element.

Let’s take this simple example. We have a parent and a child.

<div id="parent">
  <div id="child"></div>
</div>

Just to be thorough, suppose we style them with nice Christmas colors.

#parent {
  width: 50px; 
  height: 50px;
  background: green;
}
#child {
  width: 25px; 
  height: 25px;
  background: red;
}

We’ll attach an event listener to the parent element.

In order to distinguish clicking #parent from clicking #child, we can compare the event target and the event currentTarget.

document.getElementById("parent").addEventListener('click', e => {
  if(e.target !== e.currentTarget) console.log("child clicked") 
  else console.log("parent clicked")
});

e.target refers to the element that triggered the event (i.e. the element the user clicked on).

e.currentTarget refers to the element that the event listener is attached to.

In our case, e.currentTarget will always return the #parent element, but e.target will return whatever element the user directly interacted with.


Revise the code and make it more robust with proper test case and check an error there before implementing into a production environment.
If you have any questions or get stuck, please dont hesitate to reach out to me for help.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button