Skip to content

Instantly share code, notes, and snippets.

@hilios
Created November 29, 2012 14:12
Show Gist options
  • Save hilios/4169345 to your computer and use it in GitHub Desktop.
Save hilios/4169345 to your computer and use it in GitHub Desktop.
Mouse compass

Mouse compass

Display the current mouse region inside a DOM element just like a compass. See in action!

<style type="text/css">
#box {
background-color: #cccccc;
width: 50px;
height: 50px;
position: absolute;
top: 50%;
left: 50%;
margin: -25px 0 0 -25px;
text-align: center;
line-height: 3em;
}
input {
border: 1px solid #cccccc;
padding: 5px;
margin: 0 auto;
}
​</style>
<div id="box"></div>
var $box = $('#box');
$(document).mousemove(function(event) {
var x, y, boxX, boxY, boxW, boxH, boxCenterX, boxCenterY, radians, angle;
// Helper to convert radians to degrees
function radToDeg(radians) {
return (radians * 180 / Math.PI);
}
// Calculate the center of the object
boxX = $box.offset().left;
boxY = $box.offset().top;
boxW = $box.width();
boxH = $box.height()
boxCenterX = boxX + boxW / 2;
boxCenterY = boxY + boxH / 2;
// Display C(enter) if the mouse pointer is over the box area
if(event.pageX > boxX && event.pageX < boxX + boxW && event.pageY > boxY & event.pageY < boxY + boxH) {
$box.html("C");
return true;
}
// Calulate the triangle dimensions
x = event.pageX - boxCenterX;
y = boxCenterY - event.pageY;
// Find the angle in radians
radians = Math.atan(y / x);
// Correct the angle by quadrant
if(event.pageX < boxCenterX && boxCenterY > event.pageY) radians += Math.PI;
if(event.pageX < boxCenterX && boxCenterY < event.pageY) radians += Math.PI;
if(event.pageX > boxCenterX && boxCenterY < event.pageY) radians += 2 * Math.PI;
// Convert the angles to degress without significance
angle = radToDeg(radians).toFixed(0);
if(angle > 345 || angle < 015) $box.html("L");
if(angle > 015 && angle < 075) $box.html("NL");
if(angle > 075 && angle < 105) $box.html("N");
if(angle > 105 && angle < 165) $box.html("NO");
if(angle > 165 && angle < 195) $box.html("O");
if(angle > 195 && angle < 255) $box.html("SO");
if(angle > 255 && angle < 285) $box.html("S");
if(angle > 285 && angle < 345) $box.html("SL");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment