Grow your CSS skills. Land your dream job.

Last updated on:

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.

Reference URL

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.

  3. sadunaresh
    Permalink to comment#

    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)));        
        };
    
    
    $(document).ready(function(){
    
    
        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?

    • 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.

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".