0

JSFiddle example

Is there a way to trigger the click event of a div inside another div without triggering the div on the containing elements click event?

<style>
#div1 {
  background-color: black;
  height: 200px;
  width: 200px;
  position: relative;
}

#div2 {
  background-color: white;
  height: 50px;
  width: 50px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>

<div id="div1">
  <div id="div2">
  </div>
</div>

<script>
  const div1 = document.getElementById('div1')
  const div2 = document.getElementById('div2')

  div1.onclick = () => {
    console.log("Div 1")
  }

  div2.onclick = () => {
    console.log("Div 2")
  }
</script>

How can I click the inner div without triggering click event of outer div?

Jordan
  • 148
  • 7
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation –  Sep 30 '21 at 17:31
  • 2
    Duplicate: [How do I prevent a parent's onclick event from firing when a child anchor is clicked?](https://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli) –  Sep 30 '21 at 17:32

1 Answers1

1

You may add e.stopPropagation() to the event.

div2.onclick = (e) => {
  e.stopPropagation();
    console.log("Div 2")
}

enter image description here