Stop the click event from bubbling to parent elements:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>/*from w w w. java 2 s . c o m*/ <script> $(document).ready(function(){ $("span").click(function(event){ event.stopPropagation(); document.getElementById("demo").innerHTML = "The span element was clicked."; }); $("p").click(function(event){ document.getElementById("demo").innerHTML = "The p element was clicked."; }); $("div").click(function(){ document.getElementById("demo").innerHTML = "The div element was clicked."; }); }); </script> </head> <body> <p id="demo"></p> <div style="height:100px;width:500px;padding:10px;background-color:red;"> This is a div element. <p style="background-color:pink">This is a p element, in the div element. <br> <span style="background-color:orange">This is a span element in the p and the div element.</span></p></div> </body> </html>
The event.stopPropagation()
method stops the bubbling of an event to parent elements.
The event.stopPropagation()
method prevents any parent event handlers from being executed.
Use the event.isPropagationStopped()
method to check whether this method was called for the event.
event.stopPropagation()
Parameter | Optional | Description |
---|---|---|
event | Required. | The event parameter comes from the event binding function |