Converting Between Document and Viewport Coordinates

By: Dusty Arlia
Published on Saturday, August 24, 2013, 08:23 PM
Last Updated on Monday, July 06, 2015 at 3:23 PM
Total Updates: 2

If the document is smaller than the viewport or if the document hasn't been scrolled, then the document coordinates and viewport coordinates should be exactly the same. But if the document has been scrolled, then you have to calculate the coordinates by adding or subtracting the scroll offsets. The scroll offset values are held in the pageXOffset and pageYOffset properties of the window object. Or these values can be queried using the scrollLeft and scrollTop properties of the documentElement (document.documentElement) or body element in quirks mode (document.body).

Example Element:

Document Coordinates:

X: 100 (100 pixels to the right)

Y: 100 (100 pixels down)

Viewport Coordinates (After scrolling down 25px):

X: 100 (100 pixels to the right)

Y: 75 (100 pixels minus 25 pixels equals 75 pixels down)

Comments:

Ad:

Ad: