Track 02 · Lesson 4 of 17Inside the browser

Track 02 · Inside the browser

Default actions and preventDefault()

Lesson 4 of 17· 6 min

Many events come with a built-in browser behavior: links navigate, checkboxes toggle, forms submit, right-click opens a menu. preventDefault() cancels that behavior. Switch it on and off for each one.

Turn the defaults off

One switch per behavior

  • Click the checkbox.

  • Try typing letters.

  • Right-click (or long-press) here

    Right-click (or long-press) the box.

  • Submit the form.

preventDefault()

Cancels the browser’s built-in action for this event. Other listeners still run, and the event still bubbles.

stopPropagation()

Stops the event from reaching more elements up (or down) the tree. The browser’s default action still happens.

This is the note the link jumps to.

When to prevent the default#

Prevent it when JavaScript takes over the job:

  • A form submitted with fetch() instead of a full page load.
  • A link handled by a client-side router, like Next.js's Link.
  • A custom context menu, or a drag-and-drop area.

Don't prevent it just to stop people doing something. A checkbox that won't tick, or a page that blocks copy and paste, only confuses people.

Blocking keys isn't validation#

The digits-only field blocks letters as you type, but pasting still gets them in, and so does a request sent without your form at all. Blocking keys is a nicety; you still need to check the value, and on the server too. That's a lesson in Building for everyone.

Not every event can be prevented. Check event.cancelable: scrolling, for example, can't be cancelled from a passive listener.

Check yourself

What does event.preventDefault() do?