Middle
What are the phases of browser events (bubbling and capturing)? How to stop bubbling? How to prevent default action?
sobes.tech AI
Answer from AI
In the browser, an event passes through three phases:
- Capturing phase — the event moves from the root of the document to the target element.
- Target phase — the event reaches the target element.
- Bubbling phase — the event bubbles back up from the target element to the root.
To stop the event from bubbling up, use the method event.stopPropagation():
element.addEventListener('click', function(event) {
event.stopPropagation(); // stops further propagation
});
To prevent the default action (such as following a link or submitting a form), use event.preventDefault():
link.addEventListener('click', function(event) {
event.preventDefault(); // cancels the default action
});