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
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.
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With