Say you have some code like this:
<html> <head> </head> <body> <div id="parentDiv" onclick="alert('parentDiv');"> <div id="childDiv" onclick="alert('childDiv');"> </div> </div> </body> </html>
I don't want to trigger the parentDiv
click event when I click on the childDiv
, How can I do this?
Updated
Also, what is the execution sequence of these two event?
To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation . parent. addEventListener( "click", (e) => { e. stopPropagation(); console.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
You need to use event.stopPropagation()
Live Demo
$('#childDiv').click(function(event){ event.stopPropagation(); alert(event.target.id); });
event.stopPropagation()
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Without jQuery : DEMO
<div id="parentDiv" onclick="alert('parentDiv');"> <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;"> AAA </div> </div>
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