Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.4 — Default Actions
JavaScript · Example 1 of 3

Links and checkboxes

A checkbox is special: the browser flips checked before your listener runs, then flips it back if you cancel. So inside the listener, checked already shows the new value.

Many events come with a built-in browser behaviour, called the default action: a link navigates, a form sends and reloads the page, a checkbox toggles. event.preventDefault() cancels it so your JavaScript can do something else, and passive listeners promise never to cancel, which keeps scrolling smooth.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a link <a href="/delete" id="remove">Delete</a> log Are you sure? instead of navigating. Click it from code.

02

Make a text input #digits that refuses any key that isn't a digit, Backspace, Tab or an arrow key. Test it by dispatching a keydown for a and for 5 and logging whether each was cancelled.

Explain it without notes

01

What is a default action? Give three examples.

02

Why should you handle a form's submit event rather than the submit button's click?

03

What is a passive event listener and why do browsers want them?

04

What is the difference between preventDefault() and stopPropagation()?

Links and checkboxes

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

link: navigation cancelled, defaultPrevented = true
checkbox during the listener: true
checkbox after the click: false