Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate direct (diagonal) distance from center of div to the center of the screen with jquery

Hej!

Is it possible to read / calculate the direct distance between the center of a div and the center of the screen with jquery?

I don't need the distance from the div to the vertical center of the screen (only giving me the distance in height) or to the horizontal center of the screen (only giving me the distance in width), but the diagonal distance.

Is this even possible with pixels?

Thanks for the help in advance, Kind regards

Lucas

like image 814
lucasdidthis Avatar asked Oct 24 '25 12:10

lucasdidthis


1 Answers

This should work regardless of how scrolled down the page you are.

let element = document.getElementById("someId");
let elementPosition = getCenterOfElement(element);
let documentPosition = getCenterOfPage();
let result = calculateDistance(documentPosition , elementPosition);

function getCenterOfPage() {
    let x = $(document).width()/2;
    let y = $(document).height()/2;
    let coordinates = {x, y};
    return coordinates;
}
function getCenterOfElement(element) {
    let x = $(element).offset().left + $(element).outerWidth()/2;
    let y =  $(element).offset().top + $(element).outerHeight()/2;
    let coordinates = {x, y};
    return coordinates;
}
function calculateDistance(coordinates1, coordinates2) {
    let h = coordinates1.x - coordinates2.x;
    let v = coordinates1.y - coordinates2.y;
    let result = Math.sqrt(h*h + v*v);
    return result;
}
like image 135
Gabriel West Avatar answered Oct 26 '25 01:10

Gabriel West



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!