preventDefault vs stopPropagation vs return false

By

Learn the difference between preventDefault, stopPropagation, and return false in addEventListener, inline handlers, and jQuery event handlers.

~~~

Use event.preventDefault() to stop a browser action. Use event.stopPropagation() to stop the event moving through the DOM.

return false depends on how the handler was registered. It is not a general replacement for either method.

event.preventDefault() stops the browser action

A click on a link normally opens its URL. A form submission normally sends the form.

Call preventDefault() to stop that default action:

const link = document.querySelector('a')

link.addEventListener('click', event => {
  event.preventDefault()
  console.log('The link was not opened')
})

The event still propagates to ancestor elements. preventDefault() does not stop bubbling.

It also only works for cancelable events. If the listener is passive, calling it has no effect and the browser may print a warning.

event.stopPropagation() stops propagation

Suppose a button is inside a clickable container. A click on the button can also reach the container’s listener.

Call stopPropagation() to stop the event moving farther through its capturing or bubbling path:

const button = document.querySelector('button')

button.addEventListener('click', event => {
  event.stopPropagation()
  console.log('The container will not receive this click')
})

This does not cancel the browser’s default action. A link can still open and a form can still submit.

stopPropagation() also does not stop other listeners on the same element. Use stopImmediatePropagation() when you need that stronger behavior.

My event bubbling and capturing guide explains the path an event follows.

What does return false do?

With addEventListener(), the return value is ignored:

link.addEventListener('click', () => {
  return false
})

That code does not prevent navigation and does not stop propagation.

An event handler property is different. Returning false cancels the default action:

link.onclick = () => false

The same historical behavior applies to an inline handler such as onclick="return false". It cancels the default action but does not stop propagation. Prefer addEventListener() and explicit event methods in new code.

In a jQuery handler, returning false is shorthand for calling both preventDefault() and stopPropagation():

$('a').on('click', () => false)

This jQuery behavior is one reason the rule is confusing. The meaning changes with the API registering the handler.

~~~

Related posts about js: