Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for all events in JavaScript

Tags:

javascript

I'm trying to figure out how to listen for all events on a JavaScript object.

I know that I can add individual events with something like this

element.addEventListener("click", myFunction); element.addEventListener("mouseover", myFunction); ... 

I'm trying to figure out if there is a catch-all, I'd like to do something like this:

// Begin pseudocode var myObj = document.getElementById('someID');  myObj.addEventListener(/*catch all*/, myFunction);  function myFunction() {   alert(/*event name*/); } // End pseudocode 
like image 975
user3780616 Avatar asked Dec 05 '14 17:12

user3780616


People also ask

How do you list all event listeners?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

Which function is used to listen the events in JavaScript?

The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers.

Can you add multiple event listener in JavaScript?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.


2 Answers

A more modern rewrite of @roman-bekkiev's answer:

Object.keys(window).forEach(key => {     if (/^on/.test(key)) {         window.addEventListener(key.slice(2), event => {             console.log(event);         });     } }); 

Note that you can further customize what you want to catch, for example:

/^on(key|mouse)/.test(key)

like image 124
ryanpcmcquen Avatar answered Oct 23 '22 23:10

ryanpcmcquen


To pick up standard element's events.

var myObj = document.getElementById('someID'); for(var key in myObj){     if(key.search('on') === 0) {        myObj.addEventListener(key.slice(2), myFunction)     } } 

But as @jeremywoertink mentioned any other events are also possible.

like image 37
Roman Bekkiev Avatar answered Oct 24 '22 00:10

Roman Bekkiev