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.
Make a button #hello that logs Hello! each time it is clicked. Fire it twice from code.
Make a #start button whose listener logs Started only the first time it is clicked, without using { once: true }.
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
What is the difference between addEventListener and setting onclick?
Why can't you remove a listener that was added as an inline arrow function?
What does the event object contain, and how do you receive it?
What does isTrusted tell you, and why does it matter?
Preview
Console
Nothing logged yet.Expected console output
tick listener ran
arrow listener ran
Welcome! (shown once)