Skip to content

Instantly share code, notes, and snippets.

@IceCreamYou
Created June 20, 2015 23:21
Show Gist options
  • Save IceCreamYou/ed13f4319f726bdcf616 to your computer and use it in GitHub Desktop.
Save IceCreamYou/ed13f4319f726bdcf616 to your computer and use it in GitHub Desktop.
Gets the coordinates of the mouse relative to a container.
var container = document.getElementById('container'), // Pick the element(s) you care about
halfBoxSize = 0, // Facilitates placing boxes (click in the middle, get the upper-left coords)
roundPxToNearest = 5, // Snap to grid
roundPctToNearest = 0.0000001; // Precision for percentage values
container.addEventListener('click', reportLocation, false); // mousemove is another useful event
function reportLocation(event) {
var floorCoords = this.getBoundingClientRect(),
leftPx = roundPxToNearest * Math.round((event.clientX - floorCoords.left - halfBoxSize) / roundPxToNearest),
topPx = roundPxToNearest * Math.round((event.clientY - floorCoords.top - halfBoxSize) / roundPxToNearest),
left = roundPctToNearest * Math.round((100 * (leftPx / floorCoords.width)) / roundPctToNearest),
top = roundPctToNearest * Math.round((100 * (topPx / floorCoords.height)) / roundPctToNearest);
console.log('left: ' + left + '%; top: ' + top + '%;');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment