Sometimes, we want to listen for all events on an element with JavaScript.
In this article, we’ll look at how to listen for all events on an element with JavaScript.
Listen for All Events on an Element with JavaScript
To listen for all events on an element with JavaScript, we can loop through the keys of the window
object to see which property starts with on
.
Then we can take the part of the key after on
as the event name and call addEventListener
with it to listen to the event.
For instance, we can write:
Object.keys(window).forEach(key => {
if (/^on/.test(key)) {
window.addEventListener(key.slice(2), event => {
console.log(event);
});
}
});
to get the keys from window
with Object.keys
.
Then we call forEach
with a callback that takes the key
.
And if the key
starts with on
, then we call window.addEventListener
on it with the key
without the on
part, which we get with key.slice(2)
.
The 2nd argument for window.addEventListener
is the event handler callback.
Now when we do anything to the browser window, we’ll see the event object logged.
Conclusion
To listen for all events on an element with JavaScript, we can loop through the keys of the window
object to see which property starts with on
.
Then we can take the part of the key after on
as the event name and call addEventListener
with it to listen to the event.
One reply on “How to Listen for All Events on an Element with JavaScript?”
“on an Element”, but this approach doesn’t actually work for elements, or for any type that inherits properties from a prototype.
To get something that works for elements, you need to walk up the prototype and enumerate each of them:
function getAllProperties(obj: any) {
const allProps: string[] = [];
do {
const props = Object.getOwnPropertyNames(obj)
for (const prop of props) {
if (allProps.indexOf(prop) === -1) {
allProps.push(prop);
}
}
} while (obj = Object.getPrototypeOf(obj));
return allProps
}