DEV Community

R☭
R☭

Posted on

2 1

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!