Languages
[Edit]
EN

JavaScript - add event listener called only once

11 points
Created by:
Hayley-Mooney
677

In this short article, we would like to show how using JavaScript, add event that is called only once.

Quick solution:

const addOnceListener = (object, event, callback) => {
    object.addEventListener(event, callback, {once: true});
};


// Usage example:

addOnceListener(window, 'focus', (e) => { /* ... */ });

or:

const addOnceListener = (object, event, callback) => {
    const remove = () => object.removeEventListener(event, handle);
    const handle = (e) => remove() || callback(e);
    object.addEventListener(event, handle);
    return remove;
};


// Usage example:

addOnceListener(window, 'focus', (e) => { /* ... */ });

 

Practical examples

1. Embedded solution

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="button">Click me!</button>
  <script>

    function addOnceListener(object, event, callback) {
        object.addEventListener(event, callback, {once: true});
    }
    
    
    // Usage example:
    
    var button = document.querySelector('#button');

    var callback = function(e) {
        console.log('Button clicked!');
    };

    addOnceListener(button, 'click', callback);

  </script>
</body>
</html>

 

2. Custom solution

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="button">Click me!</button>
  <script>

    function addOnceListener(object, event, callback) {
        var remove = function() {
            object.removeEventListener(event, handle);
        };
        var handle = function(e) {
            remove();
			callback(e);
        };
        object.addEventListener(event, handle);
        return remove;
    }
    
    
    // Usage example:
    
    var button = document.querySelector('#button');

    addOnceListener(button, 'click', function(e) {
        console.log('Button clicked!');
    });

  </script>
</body>
</html>

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join