If a nested element fires an event, do not let the container handle it

I have a div containing another div. If the user clicks on the inner div, I want the event handler attached to this element to execute. Right now, the event handler of the inner element is executed first, and then the outer element. Is there any way to change this?

<html> <head> <meta charset="utf-8"> <title>Demo</title> </head> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script> $(document).ready(function(){ $("#containerElement").click(function(event){ alert("This comes from container"); }); $("#innerElement").click(function(event){ alert("This comes from inner element"); }); }); </script> <div id="containerElement" > This is the container <div id="innerElement" > This is the inner element </div> </div> </body> </html> 
0
source share
5 answers

You can stop the spread :

 $("#innerElement").click(function(event){ alert("This comes from inner element"); event.stopPropagation(); }); 
+2
source

Add event.stopPropagation();

 $("#innerElement").click(function(event){ alert("This comes from inner element"); event.stopPropagation(); }); 
+1
source

Returning false from the handler will prevent the bubble (among other things):

 $("#innerElement").click(function(event){ alert("This comes from container"); return false; }); 
+1
source

Add event.stopPropagation() to your innerElement event handler. See the jQuery docs for more information.

 $("#innerElement").click(function(event){ alert("This comes from inner element"); event.stopPropagation(); }); 
0
source

As mentioned above:

http://jsbin.com/avikol/2/

0
source

All Articles