Advanced Events
When events (e.g., clicks, keyboard inputs) occur on a web page, they propagate through the DOM tree, undergoing two phases known as capturing and bubbling.
Event Bubbling and Capturing
Event capturing and bubbling can be likened to a droplet falling from the top of a tree downwards (capturing) and then bouncing upward after hitting the ground (bubbling).
1. Capturing: The event starts from the topmost (parent) element and travels down to the actual element where the event occurred. For example, when a click event happens, it is dispatched in sequence from the document object down to the target element.
2. Bubbling: The event begins at the element where it occurred and travels up to the topmost (parent) element. For instance, when a button is clicked, the event is passed sequentially up to the form, section, and document body that contain the button.
Stopping Event Propagation
stopPropagation and preventDefault Methods
-
stopPropagation
: Stops the current event from propagating further.- Example: The following code prevents the click event from being passed to parent elements.
Stopping Event Propagationelement.addEventListener('click', function (event) {
event.stopPropagation();
});
-
preventDefault
: Prevents the browser’s default behavior (such as following a link, submitting a form, etc.)- Example: The following code stops the browser's default action of navigating to the URL when a link is clicked.
Preventing Default a Tag Behaviordocument.querySelector('a').addEventListener('click', function (event) {
event.preventDefault();
console.log("Link was clicked, but we're not navigating anywhere!");
});
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.