# Calculate Distance Between Mouse and 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);
});

})();``````

This code will 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.

1. Riderman

In this case the point 0 is the center of the element.
How would the point be 0 anywhere in the element?
That is, the edge of the element takes away a = 0

2. Mario

Thanks for this post – this makes life really easy.

Hi,

I was working with jquery for last 3 months.. I am well acquainted working with functionality but never tried to write a plug in… just started experimenting with above functionality.. coded as below..

``````\$.fn.calculateDistance = function(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)));
};

var mX, mY, distance, \$distance = \$('#distance span'), \$element  = \$('#element');
\$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance(\$element, mX, mY);
\$distance.text(distance);

});

});
``````

doing so gives me an error

``````calculateDistance is not defined
``````

where am I going wrong?

• Chris Coyier

You attached it to to the jQuery object (`\$.fn.calculateDistance`) so you’ll have to call it like `\$.calculateDistance`.

Or just don’t attach it like that. Different schools of thought on that. Since your function requires jQuery internally might be good to leave it like that.

4. Sonar

hi, I was wondering if it possible to move the element center to the current mouse position. any suggestions pls.

5. Sonar

In that example i want to move the circle to the position(means i want the center of circle to at the cursor position) where the cursor is currently present when i hover it.