Skip to content

Instantly share code, notes, and snippets.

@mnichols
Forked from branneman/getMousePosition.js
Created March 20, 2018 16:22
Show Gist options
  • Save mnichols/d80a8f625739256c3423c29b5b1e6a43 to your computer and use it in GitHub Desktop.
Save mnichols/d80a8f625739256c3423c29b5b1e6a43 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