Skip to content

Instantly share code, notes, and snippets.

@shamasis
Created June 7, 2014 20:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shamasis/e4f1a86be90f3a3bd062 to your computer and use it in GitHub Desktop.
Save shamasis/e4f1a86be90f3a3bd062 to your computer and use it in GitHub Desktop.
Cross browser layerX and layerY in JavaScript
/**
* 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
Copy link

s0xDk commented May 31, 2020

const bbox = e.target.getBoundingClientRect();
const x = e.clientX - bbox.left;
const y = e.clientY - bbox.top;

@adityawasudeo
Copy link

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')

@shamasis
Copy link
Author

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