How To Work Out Distance Between Mouse And Element

In the tutorial today you will learn how you can use jQuery to get the distance of the mouse from a certain element on the page. This bit of code can be useful on a small web app which has a lot of user interaction and you want an event to run when the user mouse is in a certain distance from an element. There is a demo page for this code, which has a label to show the distance in pixels and an element which we will take the center position for.

The jQuery Code

To start with we are going to create the global variables and the document ready event for this event.


(function() {

var mX, mY, distance,
$distance = $('#distance span'),
$element  = $('#element');

$(document).mousemove(function(e) {
distance = calculateDistance($element, e.pageX, e.pageY);
$distance.text(distance);
});

})();

As you can see from the code we set a function on the mouse move event so whenever the visitor moves the mouse this is ran. What we do then is use the e variable to get the X and Y position of the mouse and sent this to the function calculateDistance, with a parameter of element.

Calculate Distance

Below is the function we use which will work out the distance between the mouse position and the current element position.


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)));
}

View the demo to see this in action.

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring