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:

<div id="parent">
  <button id="myButton">Click Me!</button>
</div>
// Inside a parent element's handler:
document.getElementById('parent').addEventListener('click', (event) => {
  console.log("Parent Element Clicked!"); 
});

// Inside the button's handler:
document.getElementById('myButton').addEventListener('click', (event) => {
  console.log("Button Clicked!");
  // If you want to stop further processing, preventDefault() and/or stopPropagation():
  event.preventDefault(); // Prevents default button behavior 
  event.stopPropagation(); // Stops event from bubbling to the parent element
}); 

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