In jQuery, the .one()
method lets you attach an event handler that can only be invoked once:
const $button = $('button');
function handleClick() {
alert('This will be displayed only once.');
}
$button.one('click', handleClick);
This is so easy to do in vanilla JS. The .addEventListener()
method accepts an object of options as its third parameter. Just set the once
property to true
:
const button = document.querySelector('button');
function handleClick() {
alert('This will be displayed only once.');
}
button.addEventListener('click', handleClick, {
once: true
});
This works in all modern browsers, but not Internet Explorer (IE). If you need to support IE, you can use the .removeEventListener()
method instead:
const button = document.querySelector('button');
function handleClick() {
alert('This will be displayed only once.');
button.removeEventListener('click', handleClick);
}
button.addEventListener('click', handleClick);