DEV Community

R☭
R☭

Posted on

Javascript events, going back to the basics

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.

Top comments (0)