How To Work Out Distance Between Mouse And Element

Point a to b 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. Demo

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

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.


Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *