lucasdidthis
lucasdidthis

Reputation: 61

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

Upvotes: 4

Views: 2041

Answers (1)

Gabriel West
Gabriel West

Reputation: 941

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;
}

Upvotes: 3

Related Questions