Calc Distance Between Mouse and Element

by orrinward

HTML

<p>Move your mouse to calculate distance between the center of the element and the mouse cursor.</p>

<p id="distance">Distance: <span>0</span>px</p>

<div id="element"></div>

CSS

body {
    font: 11px helvetica, arial, sans-serif;
    text-align: center;    
}

#distance {
    font-size: 16px;
    font-weight: bold; 
    margin-top: 10px; 
}

#element {
    background: #000;
    color: #fff;
    height: 50px;
    left: 50%;
    margin: -25px 0 0 -25px;
    position: absolute;
    top: 50%;
    width: 50px;
}

JavaScript

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

})();