Question 62
Question
Explain the difference between event.preventDefault()
and event.stopPropagation()
.
Answer
event.preventDefault()
and event.stopPropagation()
give you fine-grained control over how events propagate through your web application.
1. event.preventDefault()
:
Purpose: Stops the default action associated with an event.
Examples:
Clicking a link: Prevents the page from navigating to the URL specified in the
<a>
tag.Submitting a form: Prevents the form from submitting data to the server.
2. event.stopPropagation()
:
Purpose: Stops event bubbling up the DOM tree (the chain of parent elements).
How It Works: When an event occurs, it naturally "bubbles up" from the element where it started to its parent elements, and so on. This can lead to multiple handlers being triggered for the same event.
stopPropagation()
prevents this upward propagation.
Illustrative Example:
In this example:
Without
stopPropagation()
: Clicking "Button Clicked!" would be logged, followed by "Parent Element Clicked!".With
stopPropagation()
: Only "Button Clicked!" would be logged.
Last updated