Calculate Distance Between Mouse and Element

Avatar of Chris Coyier
Chris Coyier on (Updated on )
(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);


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.