MouseEvent.path equivalent in Firefox & Safari
Asked Answered
C

2

34

I'm using Polymer 1.0 and when there is a click on a button in Chrome a MouseEvent is generated. This MouseEvent object has a path property which is an ordered array of parent elements to the clicked button. In Firefox & Safari, however, a click is generated which does not have a path property. Is there an equivalent property of the click object which gives me the same information?

Colleencollege answered 25/4, 2016 at 15:57 Comment(0)
P
42

It's not available, but if you really would like to have this property, then you could extend the native prototype of the Event object like so:

if (!("path" in Event.prototype))
Object.defineProperty(Event.prototype, "path", {
  get: function() {
    var path = [];
    var currentElem = this.target;
    while (currentElem) {
      path.push(currentElem);
      currentElem = currentElem.parentElement;
    }
    if (path.indexOf(window) === -1 && path.indexOf(document) === -1)
      path.push(document);
    if (path.indexOf(window) === -1)
      path.push(window);
    return path;
  }
});

However if I were you, I wouldn't extend the prototype - I would create a function like mentioned above instead.

Also I would change Event.prototype to MouseEvent.prototype if you want to cover only those types of events.

Pittsburgh answered 25/4, 2016 at 16:21 Comment(4)
Awesomesauce. Not exactly the answer I was looking for, but solves my issue perfectly.Colleencollege
Out of curiosity, @wogsland, what answer, or type of answer, were you hoping for?Selenaselenate
I thought there would be an equivalent property in the object created in Firefox whose name I just hadn't guessed yet.Colleencollege
@Colleencollege You could combine this answer with a check for the existence of Event.prototype.composedPath and get the best of both worlds: maximum compatibility with this code only executed in IE/Edge.Coriolanus
C
41

It seems like the e.composedPath() method might be a cross-browser version of e.path. It works in Chrome and Firefox. Not sure about Safari.

Conclave answered 17/9, 2018 at 19:8 Comment(4)
Perfect. Works in all three.Stefa
Note that it does not work on Edge or IE: caniuse.com/#feat=mdn-api_event_composedpathCatnip
It's now supported in Edge! caniuse.com/mdn-api_event_composedpathFornax
@Catnip Works in Edge.Seif

© 2022 - 2024 — McMap. All rights reserved.