Last active
July 11, 2017 10:47
-
-
Save abezhinaru/ccd5165356262b11179599c1a5b0a992 to your computer and use it in GitHub Desktop.
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
// Which HTML element is the target of the event | |
const mouseTarget = (e) => { | |
let targ; | |
e = !e ? window.event : e; | |
if (e.target) { | |
targ = e.target; | |
} else if (e.srcElement) { | |
targ = e.srcElement; | |
} | |
// defeat Safari bug | |
if (targ.nodeType == 3) { | |
targ = targ.parentNode; | |
} | |
return targ; | |
} | |
// Mouse position relative to the document | |
// From http://www.quirksmode.org/js/events_properties.html | |
const mousePositionDocument = (e) => { | |
let posx = 0; | |
let posy = 0; | |
e = !e ? window.event : e; | |
if (e.pageX || e.pageY) { | |
posx = e.pageX; | |
posy = e.pageY; | |
} else if (e.clientX || e.clientY) { | |
posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; | |
posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; | |
} | |
return { | |
x: posx, | |
y: posy | |
}; | |
} | |
// Find out where an element is on the page | |
// From http://www.quirksmode.org/js/findpos.html | |
const findOffset = (obj) => { | |
let curtop; | |
let curleft = curtop = 0; | |
if (obj.offsetParent) { | |
do { | |
curleft += obj.offsetLeft; | |
curtop += obj.offsetTop; | |
} while (obj = obj.offsetParent); | |
} | |
return { | |
left: curleft, | |
top: curtop | |
}; | |
} | |
// Mouse position relative to the element | |
// not working on IE7 and below | |
const mousePositionRelToElement = (e) => { | |
const mousePosDoc = mousePositionDocument(e); | |
const target = mouseTarget(e); | |
const targetPos = findOffset(target); | |
return { | |
x: mousePosDoc.x - targetPos.left, | |
y: mousePosDoc.y - targetPos.top | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment