2

I have a simple scenario: I have two div one inside another, I want when I click on the child div just child div invokes and when I click on parent the parent one invoke but in the example below as you can see when I click on child both are invoked.Here is my code :

$(document).ready(function(){

$("#t1").click(function(){alert("Parent")});
 $("#t2").click(function(){alert("child")});

});

http://jsfiddle.net/hminaee/hv6dv/

can anyone help?

HMdeveloper
  • 2,772
  • 9
  • 45
  • 74
  • `$(document).ready(function(){ $("#t1").click(function(){alert("Parent")}); $("#t2").click(function(e){e.stopPropagation();alert("child")}); });` http://jsfiddle.net/pranavcbalan/hv6dv/1/ – Pranav C Balan Mar 01 '14 at 05:31
  • You should try researching it before posting – Zach Saucier Mar 01 '14 at 05:31
  • possible duplicate of [Prevent execution of parent event handler](http://stackoverflow.com/questions/1398582/prevent-execution-of-parent-event-handler) – Felix Kling Mar 01 '14 at 05:54

2 Answers2

3

You should stop the event from bubbling up the DOM tree(any parent handlers from being notified of the event) using event.stopPropagation(). Try:

$(document).ready(function(){
    $("#t1").click(function(){alert("Parent")});
     $("#t2").click(function(e){e.stopPropagation();alert("child")});
});

DEMO

Kiran
  • 20,167
  • 11
  • 67
  • 99
1

You need to use e.stopPropagation() here to prevent click event buble up the DOM tree from your child div #t2 to parent div #t1

$("#t2").click(function(e){
    e.stopPropagation(); 
    alert("child")
});

Updated Fiddle

Felix
  • 37,892
  • 8
  • 43
  • 55