0

I am working on a JavaScript library for some data collection. I need to capture all click events, and want to traverse the event path looking for specific tags/ids/classes on click.

If I run the following code without the setTimeout, the event path always comes back with a single object in the array for Window. Add the setTimeout and the event path comes as expected.

window.addEventListener('click', function (event) {    
    // setTimeout with a 4ms delay to push to the end of the JS execution queue.
    setTimeout(function() {
        console.log(event.path);
    }, 4);
});
Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Jeremy H.
  • 513
  • 1
  • 5
  • 18

1 Answers1

0

You should wait for window to load, use below code so you should get the same result without the time delay:

window.onload = function() {
   document.addEventListener('click', function (event) {    
       console.log(event.path);
   });
};
Marcin
  • 1,564
  • 1
  • 13
  • 27
  • The window.onload event has already fired in my case, and this has no effect on my example. – Jeremy H. Sep 26 '16 at 16:19
  • 2
    This answer looks like it might be right for the wrong reason. loading is probably not an issue. I can replicate the problem in my javascript console on chrome using OP's code, but if I instead add the event listener to the document (not window) it works. I can't find documentation on `event.path`, but the solution might be to add the listener to the document object. – Joseph Marikle Sep 26 '16 at 16:20
  • @JosephMarikle Interesting. I am seeing the same result. If I put the event listener on the `document`, or `document.body`, the full path is populated without having to have the `setTimeout`. I still would love to have a better understanding why the path isn't populated when the listener is on the `window` – Jeremy H. Sep 26 '16 at 16:36
  • @JeremyH. You and me both. Do you have some documentation on this property? The closest I can find is [`deepPath`](https://developer.mozilla.org/en-US/docs/Web/API/Event/deepPath). – Joseph Marikle Sep 26 '16 at 16:55
  • @JosephMarikle This [SO question](http://stackoverflow.com/a/30021867/1440000) or [here](https://dom.spec.whatwg.org/#event-path). – Jeremy H. Sep 26 '16 at 17:20