JAVASCRIPT
Single-Use Event Listener with `once` Option
Learn to attach an event listener that automatically removes itself after its first execution using the `once` option, perfect for one-time interactions.
function attachOneTimeEventListener(elementId, eventType, callback) {
const element = document.getElementById(elementId);
if (!element) {
console.error(`Element with ID '${elementId}' not found.`);
return;
}
// The 'once: true' option makes the event listener automatically remove itself after being invoked.
element.addEventListener(eventType, callback, { once: true });
console.log(`One-time '${eventType}' listener attached to element '${elementId}'.`);
}
// Example Usage:
// Assume <button id="myButton">Click Me Once</button>
// attachOneTimeEventListener('myButton', 'click', () => {
// alert('This button was clicked!');
// console.log('This message will only appear once per page load for this button.');
// });
How it works: This snippet demonstrates how to create an event listener that automatically detaches itself after being triggered once. By passing `{ once: true }` as the options argument to `addEventListener()`, the event listener will execute its callback function a single time for the specified event on the given element and then be removed from that element. This is ideal for scenarios where an action should only occur on the very first user interaction.