Skip to content

Instantly share code, notes, and snippets.

@PaulKinlan
Created October 14, 2016 07:38
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save PaulKinlan/45de2fb55c1390d871b3a67f72ae730c to your computer and use it in GitHub Desktop.
Save PaulKinlan/45de2fb55c1390d871b3a67f72ae730c to your computer and use it in GitHub Desktop.
monitorEvents.js
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);
});
}
@SerkanSipahi
Copy link

ES6 Version with some optimizations (optional callback):

let monitorEvents = (el, callback) => {
  let eventCallback = callback || ((e) => console.log(e));
  let events = [];

  for(var i in el) {
    if(i.startsWith("on")) events.push(i.substr(2));
  }
  events.forEach(eventName => el.addEventListener(eventName, eventCallback)); 
}

@Krinkle
Copy link

Krinkle commented Jul 11, 2022

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.

@Krinkle
Copy link

Krinkle commented Jul 11, 2022

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