How do I prevent jQuery events from bubbling up to parent elements?

jQueryWeb DevelopmentFront End Technology

To prevent jQuery events from bubbling up to parent elements, use the stopPropogation() method. The stopPropagation() method stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event.

Example

You can try to run the following code to prevent jQuery events from bubbling up to parent elements −

Live Demo

<html>

   <head>
      <title>jQuery stopProagation() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function(event){
               alert("This is : " + $(this).text());
               event.stopPropagation();
            });
         });
      </script>
       
      <style>
         div {
            margin:20px;
            padding:20px;
            border:2px solid #666;
            width:160px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any box to see the effect:</p>
       
      <div id = "div1" style = "background-color:green;">
         OUTER BOX
         <div id = "div2" style = "background-color:gray;">
            INNER BOX
         </div>
      </div>
       
   </body>
</html>
raja
Published on 20-Dec-2017 10:10:27
Advertisements