Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `event.preventDefault()` is not working for two nested divs?

function clickOut(event) {
  event.preventDefault();
  alert('click on out');
}

function clickIn(event) {
  event.preventDefault();
  alert('click on in');
}
#out {
  width: 100px;
  height: 100px;
  border: 1px solid red;
}
#in {
  width: 50px;
  height: 50px;
  border: 1px solid blue;
}
<div id="out" onclick="clickOut(event)">
  <div id="in" onclick="clickIn(event)">
  </div>
</div>

Live demo: http://jsbin.com/qomuteyoke/1/edit?html,css,js,output

Why when I click on the inner div, there still pops two alerts, even if I've called event.preventDefault()? First is click on in, and 2nd is click on out?

like image 979
Freewind Avatar asked Dec 07 '25 03:12

Freewind


2 Answers

Try using event.stopPropagation():

jQuery def:

Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

MDN def:

Prevents further propagation of the current event.

function clickIn(event) {
    event.stopPropagation();
    alert('click on in');
}
like image 141
kemicofa ghost Avatar answered Dec 08 '25 15:12

kemicofa ghost


It's because there is no default action to prevent. Prevent default will work on anchor tags, which are used to prevent the default behaviour. What you want to do is to stop the propagation of the click, so it doesn't bubble up from the inner div. That way, if you click on the inner div, only the inner div click fires.

Replace your event.preventDefault() with event.stopPropagation().

like image 38
Skerrvy Avatar answered Dec 08 '25 15:12

Skerrvy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!