Header

Monday, 1 May 2023

How to prevent to fire parent click in jQuery/JavaScript

Hi Friends,
Today we will see how we can prevent parent click event when end user clicks on child. 

Some time it happens that we have associated click event of parent DOM element and also on click of Child DOM element. In this situation if end user clicks on Child element, then both events will be triggered. But our requirement is not firing Parent event on clicking on child element. 
<html>
    <head>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
    $(".parent").on('click',function(e){
        alert("You have called Dad");
    });
    $(".child").on('click',function(e){
          alert("You have called son");
    });
});
  </script>
    </head>
    <body>
        <div class="parent">
            <div class="child">Child where event has been added</div>
            <div>Child where no event has added </div>
        </div>
    </body>
</html>

If you run above code, it will show you two alerts on clicking on Child element. 
To resolve this issue, we will use e.stopPropagation();
This small line of code will solve the problem. 


<html>
    <head>
<script
  src="https://code.jquery.com/jquery-3.6.4.min.js"
  integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8="
  crossorigin="anonymous"></script>
  <script>
    $(document).ready(function() {
    $(".parent").on('click',function(e){
        alert("You have called Dad");
    });
    $(".child").on('click',function(e){
        e.stopPropagation();
        alert("You have called son");
    });
});
  </script>
    </head>
    <body>
        <div class="parent">
            <div class="child">Child where event has been added</div>
            <div>Child where no event has added </div>
        </div>
    </body>
</html>











No comments:

Post a Comment