I'm using this code I took from somewhere, for learning purposes. I'm trying to break it down and understand how it does what it does, if you could help me grasp it better.
This function returns the distance between mouse and the respective 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)));
}
It returns a positive number, calculating only the pixels inbetween mouse and element.
Stripping it down and leaving only the Math.floor. I don't know why without the math.sqrt(math.pow...) I get negative values depending on mouse position relaative to the element -> left(-x), right(x), above(-y), below(y) the element
and also get a different center for the element.
function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(mouseX - (elem.offset().left+(elem.width()/2)) + mouseY - (elem.offset().top+(elem.height()/2)));
}
I know what Math.pow and sqrt do on their own. I'm not seeing how they're finding the center of the element as I thought that elem.offset().left+(elem.width()/2)
was doing just that horizontally meanwhile elem.offset().top+(elem.height()/2)
did it vertically.
So 1
2 is
by adding
you get the center of the element.
You get 3 by
And you get 4 by
Finally in order to find the distance between the mouse pointer and the element you have to use good old Pythagorean theorem a²+b²=c². In order to find the square of sides 3 and 4 you use Math.pow(). About your question why is it returning a negative integer when you remove it is that the square of a number is always positive regardless if the you square a positive or a negative number. For example in this case the result for side 3 (mouseX - (elem.offset().left+(elem.width()/2)) will be negative since the mouse is to the left of the element.
This will give you the length if the distance squared, so that's why you need to use Math.sqrt to get from c² just c.
Finally Math.floor is used just to round down to the nearest integer.