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?
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');
}
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With