Child element click event trigger the parent click event

Joe.wang picture Joe.wang · Dec 20, 2012 · Viewed 123.8k times · Source

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?

Answer

Adil picture Adil · Dec 20, 2012

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.