How do you prevent event bubbling in JavaScript?
Call e.stopPropagation() in the event handler. This prevents the event from propagating to parent elements. Use it when you do not want parent handlers to fire.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Event Bubbling: Practical Use Cases
Event delegation. Instead of adding a listener to each child, add one listener to the parent. When a child is clicked, the event bubbles to the parent, which checks e.target to determine which child was clicked.
Add a click listener on the overlay. Check if e.target === overlay (the click was on the overlay, not the modal). If so, close the modal. The modal's clicks bubble to the overlay but e.target is the modal, not the overlay.
document.addEventListener('click', (e) => { /* log or intercept */ }, true). The true flag listens in the capturing phase, so the handler runs before any target handler.
Still have questions?
Browse all our FAQs or reach out to our support team
