Skip to content

Instantly share code, notes, and snippets.

@divyang4481
Forked from branneman/getMousePosition.js
Created February 19, 2018 07:25
Show Gist options
  • Save divyang4481/37e81a8594c55ee681e782c019c2e21b to your computer and use it in GitHub Desktop.
Save divyang4481/37e81a8594c55ee681e782c019c2e21b to your computer and use it in GitHub Desktop.
getMousePosition(event) - cross browser normalizing of: clientX, clientY, screenX, screenY, offsetX, offsetY, pageX, pageY
/**
* @param {Event} evt
* @return {Object}
*/
function getMousePosition(evt) {
var pageX = evt.pageX;
var pageY = evt.pageY;
if (pageX === undefined) {
pageX = evt.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
pageY = evt.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
var rect = evt.target.getBoundingClientRect();
var offsetX = evt.clientX - rect.left;
var offsetY = evt.clientY - rect.top;
return {
client: { x: evt.clientX, y: evt.clientY }, // relative to the viewport
screen: { x: evt.screenX, y: evt.screenY }, // relative to the physical screen
offset: { x: offsetX, y: offsetY }, // relative to the event target
page: { x: pageX, y: pageY } // relative to the html document
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment