Reputation: 105439
I have parent node and child node. They both have 'click' event listners. Since <a> is child element, I cannot click on it without clicking on parent <div>, so always event for parent <div> is triggered. How can I get event for child element <a> without triggering one for parent <div>?
Here is the jsFiddle and the code:
HTML
<div id="container">
<a href="" id="link"></a>
</div>
CSS:
#container {
width:100px;
height:100px;
background:blue;
position:relative;
cursor:pointer;
}
#link {
width:20px;
height:20px;
background:green;
position:absolute;
top:10px;
left:10px;
}
JS:
$('#container').on('click', function() {
alert('container');
});
$('#link').on('click', function() {
alert('link');
});
Upvotes: 2
Views: 877
Reputation: 382092
If you don't want propagation of the event to the container, use stopPropagation :
$('#container').on('click', function() {
alert('container');
});
$('#link').on('click', function(e) {
alert('link');
e.stopPropagation();
});
(if you don't want to trigger the link's default behavior, replace e.stopPropagation();
with return false;
)
Upvotes: 3