Intermediate
A keyboard listener without leaks
KeyCounter counts how many times the k key is pressed anywhere on the page, shown in #count. Its listener logs k pressed each time it handles a k.
The button #toggle hides and shows the counter. Right now, hiding it leaves the listener attached to window, so k pressed keeps being logged after the counter is gone (and showing it again adds a second listener).
Fix the effect so the listener is removed when the counter is hidden.
What Check tests
- Pressing
ktwice shows 2 - After hiding, pressing
klogs nothing - Shown again, it starts at 0 and counts each press once
- The cleanup removes the listener
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
Runs in your browser. Your code is saved here.
Your page
Press Run to see the page.
Console
Nothing logged yet.