2

Im having this problem with jquery and the layout of my html.

for example say you have a div element with id "#test" and a child element img with class "nested"

<div id="test">
  <img class="nested" src="example.jpg">
</div>

with Jquery I have two touch events,

$(document).on("click", "#test", function(){
    console.log("clicked on test id");
});

$(document).on("click", ".nested", function(){
    console.log("clicked on nested element");
});

my problem is on the second touch event, when the user clciked on nested item, this will also trigger the first element, because obviously its nested, and i don't want that to happen.

im pretty sure this is a simple problem, but i don't seem to get it.

user4739
  • 21
  • 2

3 Answers3

2

use event.stopPropagation();

 $(document).on("click", "#test", function(){
    console.log("clicked on test id");
});

$(document).on("click", ".nested", function(e){
e.stopPropagation();
    console.log("clicked on nested element");
});

reference event.stopPropagation()

Rituraj ratan
  • 10,260
  • 8
  • 34
  • 55
0

You need to stop the propagation with event.stopPropagation()

$(document).on("click", ".nested", function(e){
    e.stopPropagation();
    console.log("clicked on nested element");
});
adriaanp
  • 2,064
  • 2
  • 22
  • 40
0

Use event.stopPropagation()in the Child element click event:

event.stopPropagation():

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. add

$(document).on("click", ".nested", function(){
     event.stopPropagation()// prevents the action without notifying the parent
    console.log("clicked on nested element");
});
Somnath Kharat
  • 3,570
  • 2
  • 27
  • 51