Track 02 · Lesson 4 of 17Inside the browser
- 01Events and bubbling
- 02What fires when you click or type
- 03Keyboard, input and focus events
- 04Default actions and preventDefault()
- 05Event delegation
- 06Listener options and cleanup
- 07Custom events
- 08Debounce and throttle
- 09Events in React
- 10The event loop
- 11Don't block the main thread
- 12The rendering pipeline
- 13Core Web Vitals
- 14HTTP caching
- 15Responsive design
- 16SEO basics
- 17Service workers and offline
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
- Jump to the note at the bottom
Click the link.
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