Reputation: 2230
I am trying to add actions of div click event and I have one div enclosed inside another. and I want click event to be different for each div. but if a div is enclosed inside another, the click event on inner div does both actions, for example.. Ive added a fiddle and a sample code. How can I make it individual actions alone for each div??
$('#outerDiv').on("click",function(){
alert("s");
});
$('#innerDiv').on("click",function(){
alert("n");
});
<div id='outerDiv'><div id='innerDiv'></div></div>
Upvotes: 1
Views: 119
Reputation: 9370
Use event.stopPropagation() to prevent bubbling up of events
See Fiddle
$('#outerDiv').on("click",function(){
alert("s");
});
$('#innerDiv').on("click",function(e){
alert("n");
e.stopPropagation();
});
Upvotes: 2
Reputation: 544
Using e.StopPropagation()
will be the your solution.
You can refer to
jQuery click() on a nested div
Upvotes: 1
Reputation: 123739
Use e.stopPropagation()
to prevent the event bubble up to the parent.
This prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. By adding stopPropagation() event doesn't bubble up to its parent #outerDiv
or further up.
$('#innerDiv').on("click",function(e){
e.stopPropagation();
alert("n");
});
Upvotes: 2