Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.1 — Event Listeners
JavaScript · Example 4 of 4

onclick replaces, addEventListener adds

The onclick property is one slot: B replaced A. Listeners added with addEventListener all stay, and run in the order they were added.

An event listener is a function you register with addEventListener so the browser calls it whenever a certain event happens on an element; it receives an event object describing what happened, and removeEventListener or the once option takes it away again.

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 button #hello that logs Hello! each time it is clicked. Fire it twice from code.

02

Make a #start button whose listener logs Started only the first time it is clicked, without using { once: true }.

03

Add a listener to document that logs the id of whatever element was clicked. Click a <p id="intro"> from code.

Explain it without notes

01

What is the difference between addEventListener and setting onclick?

02

Why can't you remove a listener that was added as an inline arrow function?

03

What does the event object contain, and how do you receive it?

04

What does isTrusted tell you, and why does it matter?

onclick replaces, addEventListener adds

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

onclick B
listener 1
listener 2
same function added twice, runs once