HomeJAVASCRIPTWhat is preventDefault and stopPropagation?

What is preventDefault and stopPropagation?

These two methods are often used in JavaScript event handling, but they serve different purposes. Let’s break them down:


1. event.preventDefault()

  • Prevents the default behavior of an element.
  • Example:
    • Clicking a link (<a href="...">) navigates to another page by default.
    • Submitting a form (<form>) reloads the page by default.
  • Using preventDefault() stops these defaults, while still letting the event bubble.

Example:

document.querySelector("form").addEventListener("submit", function(event) {
  event.preventDefault(); // Stops form from submitting/reloading
  console.log("Form submission prevented!");
});

2. event.stopPropagation()

  • Prevents the event from bubbling up (or capturing down) through the DOM.
  • Useful when you don’t want parent elements’ event listeners to be triggered.

Example:

document.querySelector("#child").addEventListener("click", function(event) {
  event.stopPropagation(); // Stops click from reaching parent
  console.log("Child clicked!");
});

document.querySelector("#parent").addEventListener("click", function() {
  console.log("Parent clicked!");
});
  • If you click on #child:
    • Only “Child clicked!” appears
    • Without stopPropagation(), both “Child clicked!” and “Parent clicked!” would appear.

Key Difference

  • preventDefault() → Stops default browser action.
  • stopPropagation() → Stops event bubbling/capturing.

👉 Pro tip: Sometimes you need both:

element.addEventListener("click", function(event) {
  event.preventDefault();    // Stop default behavior
  event.stopPropagation();   // Stop bubbling
  console.log("Handled safely!");
});

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *