Register behavior without running it immediately
addEventListener associates an event type with a callback. The callback receives an event object describing the dispatch. Prefer actual interactive controls so keyboard users receive their native behavior too.
0
Each activation increments the display. The console logs click and true. Pass handleClick, not handleClick(), because the latter would invoke it during registration.
target versus currentTarget
target identifies the originating/retargeted event target. currentTarget is the element whose listener is currently running. Clicking an icon inside a button may make target the icon while currentTarget remains the button. Read a reference to currentTarget during the handler if you need it later in asynchronous code.
Listener lifetime
button.removeEventListener('click', handleClick);Removal needs the same callback identity and matching capture setting. A new arrow that looks identical is a different function. For coordinated cleanup, supported event listeners can use an AbortController signal and be removed by aborting it.
Useful options
once:true removes a listener after its first invocation. capture:true selects the capture phase. passive:true promises the listener will not call preventDefault; do not mark a listener passive if it must cancel the browser's default action.
Practice
- Add a reset button with its own handler.
- Place a span inside Add one and compare target/currentTarget.
- Register a once listener and observe that it fires once.
- Remove a listener with its original function reference and confirm the display no longer changes from it.