Last active
May 22, 2020 10:14
-
-
Save TerryZ/69eaf29aeb8ccb099e91fc2c65148bbd to your computer and use it in GitHub Desktop.
MouseEvent.path property polyfill
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* MouseEvent path property polyfill | |
*/ | |
export function MouseEventPathPolyfill() { | |
if (!('path' in Event.prototype)) { | |
Object.defineProperty(Event.prototype, 'path', { | |
get: function () { | |
const path = []; | |
let 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; | |
} | |
}); | |
} | |
} | |
/** | |
* returns the event’s path which is an array of the objects on which listeners will be invoked | |
* @param e - MouseEvent | |
* @returns {Array|EventTarget[]|*} | |
*/ | |
export function eventPath(e) { | |
if ('composedPath' in e) return e.composedPath(); | |
if ('path' in e) return e.path; | |
//polyfill | |
const path = []; | |
let currentElem = e.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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment