Jquery click inside div

I am trying to add a click event on a div that is inside li that already has a click event. I do not want the li click event to fire when the click event fires.

Here is the jsfiddle of what I'm trying to do. http://jsfiddle.net/2srUd/5/

When I click on .inside, I don't want #outside to click to shoot. I assume that I need to declare not to the selector $ (". Inside")

<script> $(document).ready(function() { $("#outside").click(function() { alert("outside click"); }); $(".inside").click(function() { alert("inside click"); }); }); </script> <ul> <li id="outside" style="border:2px solid red; padding:20px;"> <div class="inside" style="border:2px solid blue; ">Click This Div. I want to accept the inside click but not the outside click.</div> </li> </ul> 
+6
source share
2 answers

Simple fix:

  $(".inside").click(function(e) { e.stopPropagation(); alert("inside click"); }); 

http://api.jquery.com/event.stopPropagation/

Prevents bubbles from appearing in the DOM tree, preventing parent event notification handlers.

Basically, you don't want it to fire a parent event handler, so you stop propagating.

+14
source

Just do: http://jsfiddle.net/2srUd/24/

 $(document).ready(function() { $("#outside").click(function() { alert("outside click"); }); $(".inside").click(function() { alert("inside click"); return false; }); }); 
+2
source

Source: https://habr.com/ru/post/955946/


All Articles