Home > Web Front-end > JS Tutorial > body text

How to Prevent Parent Event Handlers from Executing with Child Element Clicks in jQuery?

Barbara Streisand
Release: 2024-11-23 22:55:10
Original
678 people have browsed it

How to Prevent Parent Event Handlers from Executing with Child Element Clicks in jQuery?

Preventing Execution of Parent Event Handlers

In the given HTML structure, clicking on any div element triggers the click handler of its parent div, leading to unintended behavior. To prevent this, we can disable the click event propagation using jQuery.

<div>
Copy after login
function func() {
   if ($(childId).hasClass("visible")){
    $(childId).removeClass("visible");
    $(childId).addClass("invisible");
}
Copy after login

To disable the click event propagation, add an event handler to the child elements that calls the stopPropagation() method:

function handler(event) {
    event.stopPropagation();
    // Custom code to execute for the child's click event
}

$('#a').add('#b').click(handler);
Copy after login

By preventing event propagation, clicks on child elements ('#b') will no longer trigger the parent element's click handler ('#a'). Similarly, clicks on descendant elements ('#c') will not propagate to both parent elements ('#b' and '#a').

The above is the detailed content of How to Prevent Parent Event Handlers from Executing with Child Element Clicks in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template