Listen for all events in 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

Answers:

Answer

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.

Answer

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)

Answer

You should probably pick the events you want to listen to, put them into an array and iterate over each:

['click','mouseover'].forEach(function(ev) {
    el.addEventListener(ev, function() {
        console.log('event:', ev)
    })
})
Answer

You could use EventEmitter2 which does wildcards. The problem with doing a catchall like you're talking about is that there are so many events, and you can create your own. You'd have to make an array of specifically which events you're talking about, iterate over that, and bind each one individually.

Answer
//listening for all click events on the document
   document.addEventListener('click', function (event) {

    //filtering for only events that happen on elements that contain the class
    //view_btn.          
  if (event.target.classList.contains( 'view_btn' )){
//logging out the id of the element        
          var id_of_clicked_element = event.target.getAttribute("id"); //
          console.log("button clicked has is of " + id_of_clicked_element)

        }
    });
Answer

I Hate That This Problem Persists Without A Native or Elegant Solution

Here's A Better Solution (IMHO)

This allows you to subscribe to a single CustomEvent for any EventTarget using target.addEventListener('*', ...).

    clear();

    /**
     * @param : source := EventTarget
     *  *   EventTarget.prototype
     *  *   Node (Element, Attr, etc)
     * @usage : [Node].addEventListener('*', ({ detail: e }) => {...}, false);
     */
    function proxyEventTargetSource(source) {
        var emit = source.dispatchEvent;  // obtain reference

        function proxy(event) {
            var { type } = event, any = new CustomEvent('*', { detail: event });  // use original event as detail
            if (!{ '*': true }[ type ]) emit.call(this, any);  // only emit "any" if type is not any.type ('*')
            return emit.call(this, event);
        }

        source.dispatchEvent = proxy;  // attempt overwrite

        return (source.dispatchEvent === proxy);  // indicate if its set after we try to
    }

    // proxyEventTargetSource(EventTarget.prototype);  // all targets
    proxyEventTargetSource(document);  // single target
    var e = new CustomEvent('any!', { detail: true });
    document.addEventListener('*', (e) => console.log('type: %s, original: %s, e: %O', e.type, e.detail.type, e), false);
    document.dispatchEvent(e);

Granted, a more native or [perhaps] more elegant way would be to use a native Proxy on apply for the target's dispatchEvent method, but that would maybe convey less for the sake of this post.

Hope this helps you as much as I!

Gist: https://gist.github.com/cScarlson/875a9fca7ab7084bb608fb66adff0463

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.