Joe.wang Joe.wang - 1 month ago 12
Javascript Question

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?

Answer

You need to use event.stopPropagation()

Live Demo

$('#parentDiv').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.

Comments