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.
Make a link <a href="/delete" id="remove">Delete</a> log Are you sure? instead of navigating. Click it from code.
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
What is a default action? Give three examples.
Why should you handle a form's submit event rather than the submit button's click?
What is a passive event listener and why do browsers want them?
What is the difference between preventDefault() and stopPropagation()?
Preview
Console
Nothing logged yet.Expected console output
link: navigation cancelled, defaultPrevented = true
checkbox during the listener: true
checkbox after the click: false