forEach any event whatsoever do stuff

In JavaScript, is there a command that listens to any possible event out there, and then allows you to do an action in an event handler?

Just as we can select generally any possible element out there and do an action:

document.querySelectorAll('*').forEach(element=>{
    element.style.width = "600px"
});

Is there a way to listen any possible event out there and do an action?

Pseudocode

window.listenToAnyEventWhatsoever.forEach(event=>{
    alert('Event Listened!');
});

What I have tried and didn’t work

window.addEventListener("*", ()=>{
    document.querySelector('#drupal-off-canvas-wrapper').style.width = "600px";
});

There is no built-in way to listen to all possible events on the document (or any DOM element) in JavaScript due to performance and practicality reasons. Events in JavaScript are designed to be listened to individually or in groups related by type.

However, you can create a function that adds an event listener for a predefined array of known event types. You would need to define that array yourself:

const eventTypes = ['click', 'keyup', 'keydown', // etc... ];

eventTypes.forEach(eventType => {
  document.addEventListener(eventType, (event) => {
    console.log(`Event ${eventType} listened!`);
  });
});

This will add an event listener for each event type in the eventTypes array. However, this approach is not recommended for production use due to potential performance issues and unintended side effects.

It’s better to add event listeners only for the specific events you need to handle.

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.