Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get top of current window position relative to the document body

Tags:

I am developing a model box jQuery plugin, and I need to know how to get some window properties.

The box and its shader div fade over top of the page, and the shader div covers the complete body, not just the window (Important for pages that have horizontal scroll bars). When the model div fades in, it centers itself horizontally and vertically based on the window. However, this won't work if the user scrolled down the page some ( the box will be at the top of the page since it centers based on the window size alone).

Is there a way to get the window top and left position relative to the body.
For example, the user has scrolled down the page and clicked whatever to open the model box, what can I do to get the number of pixels the top of the window is down from the top of the body.

like image 609
Robert DeBoer Avatar asked Aug 18 '09 17:08

Robert DeBoer


People also ask

How do you get an element's top position relative to the browser's viewport?

We can use the getBoundingClientRect method to get an element's position relative to its viewport. We get the div with querySelector . Then we call getBoundingClientRect on it to get an object with the top and left properties. top has the position relative to the top of the viewport.

How do you find the position of an element at the top?

The correct approach is to use element. getBoundingClientRect() : var rect = element. getBoundingClientRect(); console.

How do I get the top position of a div in CSS?

The top property affects the vertical position of a positioned element. This property has no effect on non-positioned elements. If position: absolute; or position: fixed; - the top property sets the top edge of an element to a unit above/below the top edge of its nearest positioned ancestor.


1 Answers

This should do it:

document.documentElement.scrollTop || document.body.scrollTop;
document.documentElement.scrollLeft || document.body.scrollLeft;
like image 52
kangax Avatar answered Oct 20 '22 17:10

kangax