I want to calculate the distance between the mouse and the Edges of a given element. So when the mouse touches the edge of the element the value should read 0px;
https://codepen.io/nishaljohn/pen/BVmGbz
var mX, mY, distance,
$distance = $('#distance_text p'),
$element = $('.div1');
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 takes into account the centre of the element and reads 0px only when you reach the absolute centre.
For any size element I used this code I found in another example:
var mX = e.pageX;
var mY = e.pageY;
var from = {x:mX, y:mY};
var $n=your_Element;
var off = $n.offset(),
nx1 = off.left,
ny1 = off.top,
nx2 = nx1 + $n.outerWidth(),
ny2 = ny1 + $n.outerHeight(),
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
};
var distX = to.x - from.x,
distY = to.y - from.y,
hypot = Math.sqrt(distX * distX + distY * distY);
console.log(hypot);//this will output 0 when next to your element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With