0

I've got a div inside another div. Both have event listeners attached to run a function on mousedown - call them outerDivFunction and innerDivFunction. When I click the inner div, both functions are invoked; I'd like it to only invoke innerDivFunction.

How to do this? (Vanilla solutions are preferred to jQuery.)

drenl
  • 1,321
  • 4
  • 18
  • 32
  • 1
    Check this out too https://stackoverflow.com/questions/9914587/javascript-event-delegation-handling-parents-of-clicked-elements – moon Dec 05 '17 at 00:47

1 Answers1

4

Use event's stopPropagation() in innerDivFunction. This prevents further propagation of the current event in the capturing and bubbling phases.

For more details: Event Propagation

function outerDivFunction(){
  alert('Outer Div');
}

function innerDivFunction(e){
  e.stopPropagation();
  alert('Inner Div');
}
.outer{
  border: 1px solid blue;
}
.inner{
  border: 1px solid red;
  margin: 10px;
}
<div class="outer" onclick="outerDivFunction()">Outer Div
  <div class="inner" onclick="innerDivFunction(event)">Inner Div</div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • **Avoid** at all costs the use of `Event.stopPropagation()`. An application (or third party code) should **never** stop or prevent an Event to propagate through layers, components. Rather check for `Event.target.closest("selector")` matches and act accordingly. [Example](https://stackoverflow.com/a/74812690/383904) – Roko C. Buljan Dec 15 '22 at 13:59