Skip to content

Latest commit

 

History

History
26 lines (22 loc) · 746 Bytes

addEventListenerAll.md

File metadata and controls

26 lines (22 loc) · 746 Bytes
title tags expertise firstSeen lastUpdated
Add event listener to all targets
browser,event
intermediate
2021-04-22 08:53:29 +0300
2021-04-22 08:53:29 +0300

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)
  );
};
addEventListenerAll(document.querySelectorAll('a'), 'click', () =>
  console.log('Clicked a link')
);
// Logs 'Clicked a link' whenever any anchor element is clicked