Reputation: 73
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.
Upvotes: 3
Views: 3781
Reputation: 73
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.
Upvotes: 2
Reputation:
Ok the solution is just pure math. It's just about to take away the width and the height of the container - elem.width()/2
and - elem.height()/2
(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) - elem.width()/2 + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2) ) -elem.height()/2);
}
$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance($element, mX, mY);
if(distance > 0)
$distance.text(distance);
else{
$distance.text(0);
}
});
})();
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: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>
Is this the solution?
Upvotes: 0