Created
June 7, 2014 20:40
-
-
Save shamasis/e4f1a86be90f3a3bd062 to your computer and use it in GitHub Desktop.
Cross browser layerX and layerY in JavaScript
This file contains hidden or 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
/** | |
* Get layerX and layerY of an event across all browsers without | |
* using the deprecated layerX of webkit. | |
* It stores `targetX` and `targetY` in the event, to act like `layerY` | |
* and `layerY` respectively. | |
*/ | |
getElementPosition = (function () { | |
var body = window.document.body || window.document.documentElement; | |
return function (event) { | |
var element = event.target || event.srcElement || {}, | |
left, | |
top; | |
(element.nodeType === 3) && (element = element.parentNode); | |
left = element.offsetLeft || 0; | |
top = element.offsetTop || 0; | |
// Iterate through all offset parents and accumulate their respective | |
// positions. | |
while ((element = element.offsetParent)) { | |
left += (element.offsetLeft || 0); | |
top += (element.offsetTop || 0); | |
// Adjust for the scroll position until body is reached. | |
if (element !== body) { | |
left -= element.scrollLeft || 0; | |
top -= element.scrollTop || 0; | |
} | |
} | |
// Add the coordinates to event and return. | |
return (event.targetX = left, event.targetY = top, event); | |
}; | |
}()); |
s0xDk
commented
May 31, 2020
For folks trying to get a d3.js tooltip working with bootstrap CSS (which is how I stumbled on this),
let offsetLeft = this.container.nativeElement.offsetLeft
let offsetTop = this.container.nativeElement.offsetTop
..
..
.on('mousemove', function (event: any, d: any) {
tooltip
.html('text')
.style('left', (event.offsetX+offsetLeft) + 'px')
.style('top', (event.offsetY+offsetTop) + 'px')
Oh wow! can't believe my 10 year old code is still in conversation. ❤️
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment