Child element click event trigger the parent click event

JavascriptJqueryDhtml

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Without jQuery : DEMO

 <div id="parentDiv" onclick="alert('parentDiv');">
   <div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
     AAA
   </div>   
</div>

Solution 3 - Javascript

I faced the same problem and solve it by this method. html :

<div id="parentDiv">
   <div id="childDiv">
     AAA
   </div>
    BBBB
</div>

JS:

$(document).ready(function(){
 $("#parentDiv").click(function(e){
   if(e.target.id=="childDiv"){
     childEvent();
   } else {
     parentEvent();
   }
 });
});

function childEvent(){
    alert("child event");
}

function parentEvent(){
    alert("paren event");
}

Solution 4 - Javascript

The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

You can use the method event.isPropagationStopped() to know whether this method was ever called (on that event object).

Syntax:

Here is the simple syntax to use this method:

event.stopPropagation() 

Example:

$("div").click(function(event) {
    alert("This is : " + $(this).prop('id'));
    
    // Comment the following to see the difference
    event.stopPropagation();
});​

Solution 5 - Javascript

Click event Bubbles, now what is meant by bubbling, a good point to starts is here. you can use event.stopPropagation(), if you don't want that event should propagate further.

Also a good link to refer on MDN

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoe.wangView Question on Stackoverflow
Solution 1 - JavascriptAdilView Answer on Stackoverflow
Solution 2 - JavascriptAkhil SekharanView Answer on Stackoverflow
Solution 3 - JavascriptKamuran SönecekView Answer on Stackoverflow
Solution 4 - JavascriptpalaѕнView Answer on Stackoverflow
Solution 5 - JavascriptPranavView Answer on Stackoverflow