Only fire an event once?

Qcom picture Qcom · Aug 3, 2010 · Viewed 27.2k times · Source

How do I control only firing an event once?

Actually, a quick google appears to allude to the fact that .one helps..

Answer

rofrol picture rofrol · Dec 17, 2015

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!");
});