How can I listen for an event only once in JavaScript? - 30 seconds of code
vendredi 3 novembre 2023 à 14:23Tiens, je ne savais pas qu'addEventListener acceptait des paramètres en option, en particulier un { once : true} qui permet de n'exécuter la fonction attachée à l'évènement qu'une seule fois...
const listenOnce = (el, evt, fn) =>
el.addEventListener(evt, fn, { once: true });
listenOnce(
document.getElementById('my-btn'),
'click',
() => console.log('Hello!')
); // 'Hello!' will only be logged on the first click
<link rel="stylesheet" href="http://www.warriordudimanche.net/./plugins/Galart/style.css"/>
<link rel="stylesheet" href="http://www.warriordudimanche.net/./plugins/Galart/assets/lightbox.css"/>
<script src="http://www.warriordudimanche.net/./plugins/Galart/assets/lightbox.js">
<script>[].forEach.call(document.querySelectorAll("[lightbox]"), function(el) { el.lightbox = new Lightbox(el);});► Commentaires