Home > Web Front-end > JS Tutorial > How to Prevent Event Propagation from Child to Parent Elements in HTML?

How to Prevent Event Propagation from Child to Parent Elements in HTML?

Mary-Kate Olsen
Release: 2024-12-05 04:12:09
Original
267 people have browsed it

How to Prevent Event Propagation from Child to Parent Elements in HTML?

Preventing Event Propagation with Inline Onclick Event Listener

In HTML, inline event listeners allow us to directly add event handling within the element's tag. However, sometimes we encounter situations where a child element's event should not trigger the parent element's event.

Problem:

Consider the following code:

<div onclick="alert('you clicked the header')" class="header">
  <span onclick="alert('you clicked inside the header');">something inside the header</span>
</div>
Copy after login

In this snippet, when the user clicks the span, both the span's click event and the div's click event are triggered.

Solution:

To stop event propagation from the span to the div, we can use the event.stopPropagation() method:

<span onclick="event.stopPropagation(); alert('you clicked inside the header');">something inside the header</span>
Copy after login

By calling event.stopPropagation(), we prevent the event from bubbling up to the parent element, effectively isolating the click event to the span.

Alternative for IE:

For older versions of Internet Explorer, which don't support event.stopPropagation(), we can use window.event.cancelBubble = true:

<span onclick="window.event.cancelBubble = true; alert('you clicked inside the header');">something inside the header</span>
Copy after login

This method achieves the same result by explicitly canceling the event's propagation.

The above is the detailed content of How to Prevent Event Propagation from Child to Parent Elements in HTML?. For more information, please follow other related articles on the PHP Chinese website!

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