jquery method for calculating the distance between the mouse and the specified element

  • 2020-06-22 23:49:27
  • OfStack

This article gives an example of how jquery calculates the distance between the mouse and a specified element. Share to everybody for everybody reference. Specific implementation methods are as follows:

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

Hopefully, this article has been helpful in your jQuery programming.

Related articles: