01 / 21

preventDefault &
stopPropagation

Learn to intercept browser defaults and control event flow through the DOM: two essential tools for building interactive JavaScript applications.

JavaScript

What Are Browser Events?

Every time a user interacts with a webpage: clicking a link, submitting a form, pressing a key: the browser creates an Event object. This object carries information about what happened and travels through the DOM tree.

click
User presses and releases on an element
submit
A form is submitted via button or Enter key
keydown
A keyboard key is pressed down

What Is a Default Action?

When certain events fire, the browser performs a built-in behavior automatically. These are called default actions. Sometimes you need to stop them.

1
Clicking an anchor tag navigates to its href URL
2
Submitting a form sends a request and reloads the page
3
Pressing a key in an input field types that character
4
Right-clicking opens the browser context menu

How Events Propagate

When an event fires on an element, it doesn't just stay there. It travels through the DOM in three phases:

window document
\(<\text{body}>\)
\(<\text{div}>\)
\(<\text{button}>\)
Capturing Bubbling Target Phase
1. Capturing
Event travels down from window to target
2. Target
Event reaches the clicked element
3. Bubbling
Event travels up from target to window

The preventDefault() Method

Calling event.preventDefault() tells the browser: "Do not perform your built-in action for this event." The event still propagates normally: only the default behavior is cancelled.

// Stop a link from navigating const link = document.querySelector('a'); link.addEventListener('click', function(event) { event.preventDefault(); console.log('Link clicked, but no navigation!'); });

The stopPropagation() Method

Calling event.stopPropagation() tells the browser: "Do not pass this event to any parent elements." The default action still happens: only the propagation is halted.

// Stop a click from reaching parent elements const button = document.querySelector('.inner-btn'); button.addEventListener('click', function(event) { event.stopPropagation(); console.log('Only this handler runs!'); });

Two Different Problems, Two Methods

preventDefault() Controls: Default Action Navigate to URL Propagation: still works stopPropagation() Controls: Event Flow Parent Listener Default: still works

Visualizing the Event Lifecycle

CAPTURE TARGET BUBBLE preventDefault(): cancels browser action at any phase stopPropagation(): called here at TARGET phase BUBBLE phase never runs

You can call preventDefault() at any phase to cancel the default action. Calling stopPropagation() at the target phase means the event never bubbles to parent listeners.

How to Apply Each Method

1
Identify the problem: is the browser doing something unwanted (default action) or is a parent handler interfering (propagation)?
2
Attach an event listener on the element where you want to intercept the event.
3
Accept the event object as the parameter in your callback function.
4
Call the right method: event.preventDefault() for defaults, event.stopPropagation() for flow control.
5
Add your custom logic after the call: your own navigation, validation, or UI update.

Example 1: Form Validation

Problem: when a user submits a form, the browser reloads the page. We want to validate first and only submit if valid.

const form = document.querySelector('#signup'); form.addEventListener('submit', function(event) { event.preventDefault(); // stop page reload const email = form.querySelector('#email').value; if (email.includes('@')) { // Valid: submit via fetch() instead sendData(email); } else { showError('Please enter a valid email'); } });

Example 2: Custom Navigation

Problem: you have anchor links that should trigger smooth scrolling or load content dynamically instead of navigating to a new page.

const links = document.querySelectorAll('a.smooth'); links.forEach(function(link) { link.addEventListener('click', function(event) { event.preventDefault(); const targetId = link.getAttribute('href'); const target = document.querySelector(targetId); target.scrollIntoView({ behavior: 'smooth' }); }); });

Example 3: Modal Close Button

Problem: clicking inside a modal should not close it, but clicking the overlay behind it should. Without stopPropagation, clicks bubble up to the overlay.

// Clicking the overlay closes the modal overlay.addEventListener('click', function() { closeModal(); }); // Clicking inside the modal should NOT close it modal.addEventListener('click', function(event) { event.stopPropagation(); // Click stays here, never reaches overlay });
Overlay (click → close) Modal Content Save Button stopPropagation()

Example 4: Using Both Together

Sometimes you need to cancel the default action and prevent the event from bubbling. A common case: a delete button inside a clickable list item.

// Clicking the list item opens details listItem.addEventListener('click', function() { openDetails(this.id); }); // Delete button: stop both default and bubbling deleteBtn.addEventListener('click', function(event) { event.preventDefault(); // if it's a link event.stopPropagation(); // don't open details deleteItem(this.dataset.id); });

Bonus: stopImmediatePropagation()

stopPropagation() prevents the event from reaching parent elements. But if the same element has multiple listeners, they still all fire. To stop even those, use:

button.addEventListener('click', function(event) { event.stopImmediatePropagation(); console.log('Only this handler runs'); }); // This second listener will NOT fire button.addEventListener('click', function() { console.log('I never run'); });
stopPropagation()
Stops event from reaching parent elements
stopImmediatePropagation()
Stops event from reaching any other listener, even on the same element

Common Mistakes

✕ Mixing them up
Using stopPropagation() when you meant preventDefault(): the form still submits and reloads the page.
✕ Forgetting the event parameter
Writing preventDefault() without event. in front: throws a ReferenceError.
✕ Overusing stopPropagation()
Stopping propagation everywhere breaks event delegation, analytics tracking, and other parent-level patterns.
✕ Using return false
In addEventListener, return false does nothing. It only works in inline HTML handlers (which you should avoid).

Comparison Summary

preventDefault() stopPropagation()
What it stops Browser's default action Event reaching parent elements
Event still bubbles? Yes No
Default action still happens? No Yes
Other same-element listeners fire? Yes Yes
Common use case Form validation, custom links Modals, nested click handlers
Can be used together? Yes: they are independent

Question 1 of 5

A form automatically reloads the page on submit. Which method should you call in your event listener to prevent the page reload?

Question 2 of 5

You have a button inside a <div>. Both have click listeners. You want the button click to not trigger the div's listener. What do you call?

Question 3 of 5

After calling event.preventDefault() on a link's click event, what happens?

Question 4 of 5

What is logged when the button is clicked?

Question 5 of 5

You want a delete button inside a clickable card to not navigate (the card is a link) and not trigger the card's click handler. What should you do?