Home > Web Front-end > JS Tutorial > How to Stop Event Propagation in jQuery to Prevent Parent Event Handlers from Firing?

How to Stop Event Propagation in jQuery to Prevent Parent Event Handlers from Firing?

Mary-Kate Olsen
Release: 2024-11-12 11:46:01
Original
839 people have browsed it

How to Stop Event Propagation in jQuery to Prevent Parent Event Handlers from Firing?

Preventing Propagation of Parent Event Handlers

Consider a tree structure of divs, where clicking on a parent div makes its children invisible. However, clicking on a child div also triggers the parent's click event. To address this issue, we need a way to prevent event propagation up the tree.

One effective approach using jQuery is to add a click handler to the child elements that specifically stops event propagation:

function handler(event) {
    event.stopPropagation();
    // additional code here
}

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

In this code, the stopPropagation() method is used to prevent the event from bubbling up to the parent div. When a click occurs on div '#b', the handler function is invoked, preventing the event from reaching div '#a'. Consequently, the parent's click event is not triggered, preserving the visibility of div '#c'.

The above is the detailed content of How to Stop Event Propagation in jQuery to Prevent Parent Event Handlers from Firing?. 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