Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child element click event trigger the parent click event

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?

like image 616
Joe.wang Avatar asked Dec 20 '12 06:12

Joe.wang


People also ask

How do you only trigger parent click event when a child is clicked?

To only trigger parent click event when a child is clicked with JavaScript, we call stopPropagation . parent. addEventListener( "click", (e) => { e. stopPropagation(); console.

How do you trigger a click element?

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.


2 Answers

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.

like image 56
Adil Avatar answered Sep 20 '22 07:09

Adil


Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">    <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">      AAA    </div>    </div> 
like image 33
Akhil Sekharan Avatar answered Sep 20 '22 07:09

Akhil Sekharan