Source: HariSeldon, post #2, Yoshiii, post #3
It’s super cool that addEventListener lets us have multiple handlers for the same event, like Hariseldon mentioned in the quiz discussion (JS Quiz: Easy: Simplest DOM event listener - #2 by HariSeldon). That’s a huge upgrade from the old onclick days! I was playing around with it and thought, what if we want to temporarily listen for something? Or maybe just once? removeEventListener is great for cleanup, but once makes it even cleaner for single-shot actions. It’s so handy for things like intro animations or one-time user prompts.
Here’s a quick example where a button changes color only on its first click, then stops listening:
<button id="myTemporaryButton">Click me once!</button>
const myTemporaryButton = document.getElementById('myTemporaryButton');
const handleClickOnce = () => {
myTemporaryButton.style.backgroundColor = 'lightcoral';
myTemporaryButton.textContent = 'Clicked!';
console.log('This handler ran only once!');
};
myTemporaryButton.addEventListener('click', handleClickOnce, { once: true });
// Try clicking multiple times, it only fires the first time.