Created
June 20, 2015 23:21
-
-
Save IceCreamYou/ed13f4319f726bdcf616 to your computer and use it in GitHub Desktop.
Gets the coordinates of the mouse relative to a container.
This file contains 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
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