1

Is it possible to listen to all events that are triggered on a DOM element no matter the name of the event? And if its possible is there any reason one should no do that?

Unfortunately I was not able to find anything about that in either Stack Overflow or Google :(

I am planning to write a script that needs to respond to about two dozens different custom events and I was wondering if, instead of binding each event to the element I could just listen for all of them and then based on the event name, dynamically call a function..

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Kriesi
  • 141
  • 1
  • 9
  • 2
    possible duplicate of [Listen to all javascript events](http://stackoverflow.com/questions/3489433/listen-to-all-javascript-events) – James Donnelly Jan 31 '14 at 17:04
  • 1
    This sounds like you're trying to solve the wrong problem. Can you give some context? – Halcyon Jan 31 '14 at 17:05
  • @JamesDonnelly: OP said they couldn't find anything! Stop embarrassing them! – musefan Jan 31 '14 at 17:06
  • What problem are you really trying to solve? – jfriend00 Jan 31 '14 at 17:08
  • PS: since its been flagged as a possible duplicate of [link](http://stackoverflow.com/questions/3489433/listen-to-all-javascript-events): thats not what I am trying to do. The thread in question ask: "Is it possible to listen to all javascript events?" I want more than listening/printing, I want to execute a function whenever an event triggers... – Kriesi Jan 31 '14 at 17:11
  • I am planning to write a script that needs to respond to about 2 dozens different custom events and I was wondering if, instead of binding each event to the element I could just listen for all of them and then based on the event name, dynamically call a function... – Kriesi Jan 31 '14 at 17:28
  • 1
    @Kriesi unfortunately no, you need to declare all the events you're interested in listening. – Roko C. Buljan Jan 31 '14 at 18:09

1 Answers1

2

You can't do it in the way you've suggested but this is a simple alternative:

const events = 'click mouseover mouseout';

events.split(' ').forEach(e => window.addEventListener(e, doStuff));

function doStuff(){...}