user1371896
user1371896

Reputation: 2230

adding click events separate for enclosing divs

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??

http://jsfiddle.net/Dk8vA/

$('#outerDiv').on("click",function(){
     alert("s");    
 });

$('#innerDiv').on("click",function(){
  alert("n");
});
 <div id='outerDiv'><div id='innerDiv'></div></div>

Upvotes: 1

Views: 119

Answers (3)

Anujith
Anujith

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

user1790464
user1790464

Reputation: 544

Using e.StopPropagation() will be the your solution.

You can refer to

jQuery click() on a nested div

Upvotes: 1

PSL
PSL

Reputation: 123739

Use e.stopPropagation() to prevent the event bubble up to the parent.

Reference Here

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");

});

Demo

Upvotes: 2

Related Questions