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.

Comments

  1. User Avatar
    Riderman
    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. User Avatar
    Mario
    Permalink to comment#

    Thanks for this post – this makes life really easy.

  3. User Avatar
    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?

    • User Avatar
      Chris Coyier
      Permalink to comment#

      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. User Avatar
    Sonar
    Permalink to comment#

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

  5. User Avatar
    Sonar
    Permalink to comment#

    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.

    Can u please help me in solving the problem..

    Thanks

  6. User Avatar
    Brecht
    Permalink to comment#

    I was trying to use this code to make something rather special. A div calculating height until mouse position in combination with rotating. No luck so far, but if you have any ideas, feel free to share :)

    codepen can be found here:
    See the Pen Afxlz(@sugomi) on CodePen.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag