One-Time Event Listener in JavaScript

June 20, 2020

Consider you have a button

<button type="button" id="btn">One time</button>

In some case, you need an event handler to be executed only once . You can do that by 2 Ways

1. Passing once option to addEventListener method

let button = document.getElementById("btn");
function test(){
    console.log("You cannot see me again");
}
button.addEventListener("click", test, {once : true});

When you set once:true the listener would be automatically removed when invoked.


2.Using removeEventListener

Another way is to manually remove the eventListener once the event is captured for the first time. You can use removeEventListener method to remove an event on the element;

function automaticEventRemover(ev) {
    console.log("You cannot see me again");
    e.target.removeEventListener(ev.type, arguments.callee);
}

button.addEventListener("click", automaticEventRemover);
  • ev.type denotes the type of the event, In our case, the value will be click.
  • arguments.callee is the reference of currently executing function

Create a function that will add one-time event

function one(el, eventType, eventHandler) {
    el.addEventListener(eventType, eventHandler, {once:true});
}

one(button, "click", ()=> {console.log("test")} )

Using jQuery

If you're using jQuery, then you can use one method

let button = $("#btn");
button.one("click", function () {
    console.log("You cannot see me again");
});

Please donate here, for making more tutorials.