Advanced Event Handling
When an event (e.g., click, keyboard input) occurs on a web page, it propagates through the DOM tree, passing through two phases: capturing and bubbling.
Event Bubbling and Capturing
Event capturing and bubbling can be imagined as a water droplet falling from the top of a tree down to the ground (capturing) and then bouncing back up from the ground (bubbling).
1. Capturing: The event starts from the highest (parent) element and travels down to the element that actually triggered the event. For example, when a click event occurs, the event starts from the document
object and travels down to the target element.
2. Bubbling: The event starts from the element that actually triggered the event and travels up to the highest (parent) element. For example, when you click a button, the event bubbles up to the form, section, and the main body of the page that contains the button.
Stopping Event Propagation
stopPropagation and preventDefault Methods
-
stopPropagation
: Stops the event from further propagating- Example: The code below prevents the click event from propagating to parent elements.
Stop Event Propagationelement.addEventListener('click', function (event) {
event.stopPropagation();
});
-
preventDefault
: Prevents the browser's default action (e.g., link navigation, form submission)- Example: The code below prevents the browser's default action of navigating to a URL when a link is clicked.
Prevent Default Action on Link Clickdocument.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.