Command Palette

Search for a command to run...

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

Removing listeners, and once

Two functions with identical code are still two different objects, so removeEventListener found nothing to remove in part 2.

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?

Removing listeners, and once

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

tick listener ran
arrow listener ran
Welcome! (shown once)