addMultipleListeners

JavaScript, Browser, Event

Adds multiple event listeners with the same handler to an element.

  • Use Array.prototype.forEach() and EventTarget.addEventListener() to add multiple event listeners with an assigned callback function to an element.
const addMultipleListeners = (el, types, listener, options, useCapture) => {
  types.forEach(type =>
    el.addEventListener(type, listener, options, useCapture)
  );
};
addMultipleListeners(
  document.querySelector('.my-element'),
  ['click', 'mousedown'],
  () => { console.log('hello!') }
);

Recommended snippets

  • on

    JavaScript, Browser

    Adds an event listener to an element with the ability to use event delegation.

  • listenOnce

    JavaScript, Browser

    Adds an event listener to an element that will only run the callback the first time the event is triggered.

  • addEventListenerAll

    JavaScript, Browser

    Attaches an event listener to all the provided targets.