DEV Community

loading...

Javascript events, going back to the basics

R☭
Development anarchy ↙↙↙ http://pronoun.is/he
・1 min read

In my previous post i wanted to discuss a way of a single event handler on document level that would listen to click events on certain elements or its children. By traversing the event.path i would check if in the path there was a class and then call a function if that was true.

While this works in Chrome, event.path is not widely supported, so i had to go back and implement a different solution, this time, by using event.parentElement.

    document.addEventListener('click', function(event) {
        let element = findAncestor(event.target, '.message');

        if (element) {
                  runFunction();
        }
    });

    function findAncestor(element, sel) {
      while ((element = element.parentElement) && !((element.matches || element.matchesSelector).call(element,sel)));
      return element;
    };

Enter fullscreen mode Exit fullscreen mode

It is possible to use a polyfill apprently, and there is something like event.composedPath, more about that on Stack Overflow - event.path undefined with Firefox.

Discussion (0)