Files
30-seconds-of-code/snippets/addEventListenerAll.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

722 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
addEventListenerAll browser,event,intermediate 2021-04-22T08:53:29+03:00 2021-04-22T08:53:29+03:00

Attaches an event listener to all the provided targets.

  • Use Array.prototype.forEach() and EventTarget.addEventListener() to attach the provided listener for the given event type to all targets.
const addEventListenerAll = (targets, type, listener, options, useCapture) => {
  targets.forEach(target =>
    target.addEventListener(type, listener, options, useCapture)
  );
};
addAllEventListeners(document.querySelectorAll('a'), 'click', () =>
  console.log('Clicked a link')
);
// Logs 'Clicked a link' whenever any anchor element is clicked