Skip to content

Instantly share code, notes, and snippets.

@lizardking8610
Created May 18, 2017 16:55
Show Gist options
  • Select an option

  • Save lizardking8610/f3086a7fc7293a28ba598cf9d2aef286 to your computer and use it in GitHub Desktop.

Select an option

Save lizardking8610/f3086a7fc7293a28ba598cf9d2aef286 to your computer and use it in GitHub Desktop.
jQuery: determine distance of mouse from element
(function() {
var mX, mY, distance,
$distance = $('#distance span'),
$element = $('#element');
function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
}
$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance($element, mX, mY);
$distance.text(distance);
});
})();
@lizardking8610

Copy link
Copy Markdown
Author

"calculate the distance between the mouse cursor and the center of an element. This can be useful for triggering a function when the mouse is within a certain distance of an element. Or, you can base the value of a property, such as the width, height, or opacity of the element, on the proximity of the mouse cursor." https://css-tricks.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment