Created
October 14, 2016 07:38
-
-
Save PaulKinlan/45de2fb55c1390d871b3a67f72ae730c to your computer and use it in GitHub Desktop.
monitorEvents.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function monitorEvents(element) { | |
var log = function(e) { console.log(e);}; | |
var events = []; | |
for(var i in element) { | |
if(i.startsWith("on")) events.push(i.substr(2)); | |
} | |
events.forEach(function(eventName) { | |
element.addEventListener(eventName, log); | |
}); | |
} |
For context, this Gist started with Paul Kinlan's 2016 blogpost.
The below is a simpler version:
// https://stackoverflow.com/a/72945018/319266 by @Krinkle
function monitorEvents(element) {
for (const key in element) {
if (key.startsWith('on')) {
element.addEventListener(key.slice(2), console.log);
}
}
}
Changes: remove unneeded wrapper fn as browsers prebind console nowadays, avoid string substr (now deprecated), and remove unneeded array and loop.
The most common use is to monitor the document. The following snippet directly does just that:
// https://stackoverflow.com/a/72945018/319266
for (const key in document) if (key.startsWith('on')) document.addEventListener(key.slice(2), console.log);
The benefit of a function is to be able to monitor only part of the page (to reduce noise from unrelated areas), and to be able to unmonitor it without having to reload the page.
Below is a modified version that includes the missing unmonitorEvents()
function to do exactly that.
// Usage:
// monitorEvents(document)
// monitorEvents(document.querySelector('#app'))
// unmonitorEvents(...)
//
// https://stackoverflow.com/a/72945018/319266
function monitorEvents(element) {
for (const key in element) {
if (key.startsWith('on')) {
element.addEventListener(key.slice(2), monitorEvents.log);
}
}
}
monitorEvents.log = (e) => console.log(e);
function unmonitorEvents(element) {
for (const key in element) {
if (key.startsWith('on')) {
element.removeEventListener(key.slice(2), monitorEvents.log);
}
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ES6 Version with some optimizations (optional callback):