11

If I remember correctly, I once saw a method to bind event listeners to every single element that matches a certain criteria, a query selector maybe. Looking for it again I cannot find anything other than people highly dependent on jQuery but I prefer a real simple way to achieve this.

Anyone knows what is this method called?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

8

I wrote a more general-purpose function which takes a selector, event-type, and a handler function, akin to jQuery's on function:

/** adds a live event handler akin to jQuery's on() */
function addLiveEventListeners(selector, event, handler){
    document.querySelector("body").addEventListener(
         event
        ,function(evt){
            var target = evt.target;
            while (target != null){
                var isMatch = target.matches(selector);
                if (isMatch){
                    handler(evt);
                    return;
                }
                target = target.parentElement;
            }
        }
        ,true
    );
}

For example, the following will be called for any click on a div, even if it was added to the DOM at a later time:

addLiveEventListeners("div", "click", function(evt){ console.log(evt); });

This works on all modern browsers and Microsoft Edge. To make it work in IE9 -- IE11 the test target.matches(selector) should be modified like so:

var isMatch = target.matches ? target.matches(selector) : target.msMatchesSelector(selector);

and then the test if (isMatch) will work for those browsers as well.

See also my answer for Adding event listeners to multiple elements which adds the event listeners to the elements themselves rather than to body.

isapir
  • 21,295
  • 13
  • 115
  • 116
  • 1
    This answer may be getting a bit old, but you can furthermore mimic jQuery's "on" method by replacing the call to handler by this : `handler.call(target, evt);` This way you get the same behavior where `this` refers to the element firing the event according to your selector, while you still get the original target in the event's properties. – SetsunaDilandau Feb 07 '20 at 19:28
6

The method you are looking for is called event capturing. You can do it like this:

document.querySelector('body').addEventListener('click', function(evt) {
    // Do some check on target
    if ( evt.target.classList.contains('some-class') ) {
        // DO CODE
    }
}, true); // Use Capturing
TbWill4321
  • 8,626
  • 3
  • 27
  • 25
  • I remember what I saw was a bit more sophisticate but I see your solution will work well enough so I am picking it while nothing better comes up. Thanks. –  Nov 24 '15 at 16:07
  • So, the "capturing" part will ensure that it will work if I click on a child element? – Mojimi Aug 16 '20 at 18:42