Home > Enterprise >  Targetting a container without targetting its children
Targetting a container without targetting its children

Time:10-24

I have this:

<div onclick="myFunc()" style="height:200px;width:200px;">
  <button></button>
</div>

I want myFunc to execute when any place on the div is clicked EXCEPT for the button. How can I do this?

CodePudding user response:

On the button's click event, you need to cancel propagation. Or stop 'bubbling up'.

See https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

So on your button's click event - you need something like:

function button_click(event) {
    event.stopPropagation();
    console.log("button clicked.");
  }

By default, an element's click event gets passed to its parent.

CodePudding user response:

document.querySelector('#mydiv').addEventListener('click', myFunc)

function myFunc(event) {
  if (event.target.tagName !== 'BUTTON') {
    console.log('works')
  }
}
#mydiv {
  background: red;
  height: 200px;
  width: 200px;
}
<div id="mydiv">
  <button>click me</button>
</div>

CodePudding user response:

If your contents are going to be more complex than just a single button and you want to make sure you're only running when you click on the parent element, you could use: e.target === e.currentTarget to detect when the event is occurring on that element specifically. (Documentation: target, currentTarget)

This avoid having to check for every child element, or prevent every child from propagating events. (But if you only have a single child element, one of the other answers would be simpler)

document.getElementById('example').addEventListener('click', myFunc)

function myFunc(e) {
  if (e.target === e.currentTarget) {
    console.log('Parent div clicked')
  }
}
#example {
  width: 100px;
  height: 100px;
}

div,
span {
  border: 1px solid #555;
}
<div id="example">
  <button>A</button>
  <div>B</div>
  <span>C</span>
</div>

  • Related