-2

I have one question:

  • I just started learning JS. How can I write a document or window event listener that will listen for 'any' event and output it to the console?

    window.addEventListener('don't put event here', callback, false);

I really don't know how to listen to any window or document event. I checked this Listen for all events in JavaScript someone suggested but I don't understand much of it.

Thanks.

Thank you, Matt

Musicman
  • 49
  • 6
  • 3
    Does this answer your question? [Listen for all events in JavaScript](https://stackoverflow.com/questions/27321672/listen-for-all-events-in-javascript) – aerial Nov 16 '21 at 13:52
  • What have you tried so far to solve this on your own? – Andreas Nov 16 '21 at 13:53
  • I looked at the link you gave me but didn't really understand what was going on there. I am trying to do something like: ``` window.addEventListener('generic event or leave empty?', callback, false)``` I have just started to learn JS. The link I checked out was a bit confusing. – Musicman Nov 16 '21 at 14:09
  • Is there any way to broaden event listeners to mouse events? `window.addEventListener('MouseEvent', callback, false);` – Musicman Nov 16 '21 at 14:25
  • The example you don't understand loops through all the keys in the window object, and if the key is an event (starting with `on`, hence the RegExp `/^on/`), then add an event listener. The first argument for the event listener is the event name starting with `on`, sans the `on`: `eventName.slice(2)`. – code Jan 24 '22 at 02:40

1 Answers1

0

I found a semi-solution to this problem. Basically, adding an array of events to the document model. The following code is basically the only way I know how to do this:

myArray = ['click', 'mouseover', 'keydown' /*other events */];
myArray.forEach(function (ev) {
  document.addEventListener(ev, function (event) {
    console.log('event:', ev, event.target);
  });
});

Basically, add a listener to every element in the DOM.

Musicman
  • 49
  • 6