Vanilla JS equivalent to jQuery $.once()?

Viewed 780

Working on a Drupal 9 site and trying to add some custom JS code to a page.

Drupal.behaviors.syfyGlobalHideMenu = {
  attach: function (context, settings) {
    $('.nav-flyout', context).once('remove-modals', function () {
      $(document).keyup(function (e) {
        if (e.keyCode == 27) {
          $('.nav-flyout', context).removeClass('js-flyout-active');
        }
      });
    });
  }
};

Wondering if there's a vanilla JS equivalent to the jQuery .once functionality above? Currently Drupal attaches the event listener multiple times and I am trying to avoid that as I only want to attach the event listener once but have it remain attached and run every time the event is invoked.

let intervalID = null;
const search = document.querySelector(".call-us-table input#edit-search");

search.addEventListener("keydown", event => {
  form.setAttribute("onsubmit", "return false");
  clearInterval(intervalID);
});
search.addEventListener("keyup", event => {
  intervalID = setInterval(submitForm, 2000);
});
1 Answers

Jquery once adds an html attribute to check if is the first time to run.

function vanillaOnce() {
  if (!document.body.getAttribute('data-once')) {
    document.body.setAttribute('data-once', 'true');
    return true;
  } else {
    return false;
  }
}

if (vanillaOnce) {
  console.log('runs only once');
}
Related