2

I have 2 divs with a js click event. One div is located in the other one.

But I dont want the outer div's click event to be triggered if I click the inner one. How can I prevent that?

  • 1
    Possible duplicate of [Prevent execution of parent event handler](http://stackoverflow.com/questions/1398582/prevent-execution-of-parent-event-handler) – Nirpendra Patel Apr 26 '16 at 15:07

3 Answers3

4

By default, event handling starts at the lowest level of the DOM where you have defined a handler to handle the target event. Assuming you have defined event listeners higher in the parent chain to handle the same event, you will need to stop the propagation of the event if you do not wish for the event to be handled beyond the layer you intend for it to be handled in:

e.stopPropagation();

See what happens when you remove that line in the example below:

document.querySelector('.inner').addEventListener('click', function(e) {
  alert('inner div clicked!');
  e.stopPropagation();
});

document.querySelector('.outer').addEventListener('click', function() {
  alert('outer div clicked!');
});
.outer {
  width: 200px;
  height: 200px;
  background: blue;
}

.inner {
  width: 100px;
  height: 100px;
  background: green;
}
<div class='outer'>
  Outer
  <div class='inner'>
    Inner
  </div>
</div>
timolawl
  • 5,434
  • 13
  • 29
1

Use event.stopPropagation();

Like this

document.getElementById("#seconddiv").addEventListener("click", function($event){
    $event.stopPropagation();
});
Vaibhav Jain
  • 687
  • 4
  • 15
  • thx :) but after some research I found a better way to directly call the inner div's click event without triggering the outer one's one. It looks like `$('.class1').add('.class2').click(some_function);` the problem is now that I need to call the click event on the document because my div isn't existing if my js code is read. `$(document).on('click', ".class2", function(e){});` how can I call `$('.class1').add('.class2').click(some_function);` on the document? – dunnohowishouldnamemyself Apr 26 '16 at 15:28
1

Use event.stopPropagation:

document.getElementById('inner').addEventListener('click', function (event){
    event.stopPropagation();
    console.log ('Inner div clicked!');
});

https://jsfiddle.net/4L87qLte/

abel
  • 133
  • 7