Calc Distance Between Mouse and Element JS Vanilla

Original: https://jsfiddle.net/v2mL395q/

by Léo Durand

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: 150px;
    	-webkit-transition: 0.4s ease all;

}

JavaScript

"use strict";

window.addEventListener('load', setup);
window.addEventListener('mousemove', function(e) {
  mouseMoved(e, document.getElementById('element'));
});
window.setInterval(testFunction, 100); // Pour tester d'afficher la valeur depuis ailleurs

var display, hypot;

function setup() {
  display = document.getElementById('distance');
}

function mouseMoved(evt, myElement) {
  let mX = evt.pageX,
    mY = evt.pageY,
    from = { x: mX, y: mY },
    off = myElement.getBoundingClientRect(),
    ny1 = off.top + document.body.scrollTop, //top
    ny2 = ny1 + myElement.offsetHeight, //bottom
    nx1 = off.left + document.body.scrollLeft, //left
    nx2 = nx1 + myElement.offsetWidth, //right
    maxX1 = Math.max(mX, nx1),
    minX2 = Math.min(mX, nx2),
    maxY1 = Math.max(mY, ny1),
    minY2 = Math.min(mY, ny2),
    intersectX = minX2 >= maxX1,
    intersectY = minY2 >= maxY1,
    to = {
      x: intersectX ? mX : nx2 < mX ? nx2 : nx1,
      y: intersectY ? mY : ny2 < mY ? ny2 : ny1
    },
    distX = to.x - from.x,
    distY = to.y - from.y;

    hypot = ((distX ** 2 + distY ** 2) ** (1 / 2)) / 512;


  if (hypot >= 0 && hypot < 0.1) {
    hypot = 1;
  } else if (hypot > 0.1 && hypot < 0.2) {
    hypot = 0.9;
  } else if (hypot > 0.2 && hypot < 0.3) {
    hypot = 0.8;
  } else if (hypot > 0.3 && hypot < 0.4) {
    hypot = 0.7;
  } else if (hypot > 0.4 && hypot < 0.5) {
    hypot = 0.6;
  } else if (hypot > 0.5 && hypot < 0.6) {
    hypot = 0.5;
  } else if (hypot > 0.6 && hypot < 0.7) {
    hypot = 0.4;
  } else if (hypot > 0.7 && hypot < 0.8) {
    hypot = 0.3;
  } else if (hypot > 0.8 && hypot < 0.9) {
    hypot = 0.2;
  } else if (hypot > 0.9 && hypot < 10) {
    hypot = 0.1;
  } else {
    hypot = 0;
  } 
}

function testFunction() {
  display.textContent = hypot;
  document.getElementById('element').style.opacity = hypot;
console.log(hypot);
}