Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS equivalent for jQuery one()

Can someone point me towards a solution for the following? I'm trying to find a JS equivalent for this jQuery code:

var formSelector = 'my selector here';
var attribute = 'name';
var formHistory = [];

$(formSelector).one('focusout', function(e) {
    formHistory.push(e['target'].getAttribute(attribute));
});
like image 247
quarrazzella Avatar asked Mar 30 '16 14:03

quarrazzella


2 Answers

Update

In most browsers you can now pass in once: true in an options object:

document.getElementById('btn').addEventListener('click', () => {
  console.log('Hello and goodbye');
}, {
  once: true,
});
<button id="btn">Click me</button>

Old way

In the eventlistener callback, just destroy the event listener :) Here's a helper function:

function oneTimeEvent(element, eventType, callback) {
  element.addEventListener(eventType, function(e) {
    e.target.removeEventListener(e.type, arguments.callee);
    return callback(e);
  });
}

var btn = document.querySelector('button');
oneTimeEvent(btn, 'click', function () {
  alert('♫ You clicked me once, but I won\'t let you click me twice, yeah!');
});
<button>Click me!</button>
like image 160
Phillip Avatar answered Sep 20 '22 19:09

Phillip


You could use once: true in the options parameter passed to addEventListener().

Browser support: Chrome 55+, Firefox 50+, Safari 10, Edge 16, IE not supported.

document.getElementById('foo').addEventListener('click', function(e) {
  alert('This will be displayed only once.');
}, { once: true });
<button id="foo">Click me</button>

Reference:

like image 30
sch Avatar answered Sep 22 '22 19:09

sch