Search code examples
javascripthtmldomaddeventlistener

trigger event only on parent click not child


Consider the following code as an example:

<div id="parent">
  <div id="child">info goes here</div>
</div>

//javascript
function something{
//do something;}
//initial attempt
document.getElementById('parent').addEventListener('click',something);
//event capture
document.getElementById('parent').addEventListener('click',something,true);

When I click on the parent element I would like it to do something, and when I click the child I want it to do nothing. The problem is that when I click in the child element it is triggering 'something'. I thought that it may be event bubbling, such that if I clicked on the child element, the event would bubble up from there to the parent. So then I was thinking about an event capture, but that also causes this problem.

Any advice or suggestions on how to accomplish this would be greatly appreciated.


Solution

  • Use event.stopPropagation to stop event bubbling:

    function something() {
      console.log("something");
    }
    document.getElementById('parent').addEventListener('click', something);
    document.getElementById('child').addEventListener('click', e => e.stopPropagation());
    <div id="parent">
      Parent info goes here!
      <div id="child">Child info goes here!</div>
    </div>