Only fire an event once?

Use once if you don’t need to support Internet Explorer:

element.addEventListener(event, func, { once: true });

Otherwise use this:

function addEventListenerOnce(target, type, listener, addOptions, removeOptions) {
    target.addEventListener(type, function fn(event) {
        target.removeEventListener(type, fn, removeOptions);
        listener.apply(this, arguments);
    }, addOptions);
}

addEventListenerOnce(document.getElementById("myelement"), "click", function (event) {
    alert("You'll only see this once!");
});

Leave a Comment