treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Calculate Distance Between Mouse and Element

Last 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);
        $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.

Reference URL

View Comments

Comments

  1. Permalink to comment#

    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
    Permalink to comment#

    Thanks for this post – this makes life really easy.

Leave a Comment

Use markdown or basic HTML and be nice.