JavaScript: how to implement the jQuery one() method

It's not difficult in JavaScript to make an event fire just once.

jQuery provides us with the one() method. Here's our implementation:


'use strict';

const one = ( element, evtName, callback ) => {
	
  element.addEventListener( evtName, e => {
	e.preventDefault();
	if( !element.dataset.fired ) {
		callback();
		element.dataset.fired = true;
	}
   }, false);
};

Through a simple boolean flag we can execute our code just once on a given element.

Back to top