logo
post image

jQuery offset() in Pure Javascript

jQuery's offset() method gives the top-left position of the element relative to the whole document. In Javascript there is no native method that directly gives this value, we need to calculate it.

Getting Position Relative to the Screen

Javascript has the native get​Bounding​Client​Rect() method to get the position of the element relative to the viewport (screen).

The screen can hold only a section of the whole document. If the HTML document is a short one, then the screen can adjust the complete document. However if the document is a long one, the screen will show us a part of the document and scrollbars. Using scrollbars we can scroll through the whole document.

Getting the Scroll Position of the Document

There are native methods that can get the amount by which the document is scrolled :

  • window.scrollY gives the amount by which the document has been scrolled vertically. For example a value of 0 denotes that the document has not been scrolled currently (or there may be no vertical scrollbar present). A value of 50 denotes that the browser window has been scrolled by 50px.
  • window.scrollX gives the amount by which the document has been scrolled horizontally. A value of 0 denotes that the document has not been scrolled horizontally (or there may be no horizontal scrollbar present). A value of 100 denotes that browser window has been scrolled horizontally by 100px.

Calculating offset()

If we think a bit, we will understand that :
position of element relative to document = position of element relative to screen + window scrolling position

var rect = document.querySelector("#container").getBoundingClientRect();

var offset = { 
                top: rect.top + window.scrollY, 
                left: rect.left + window.scrollX, 
            };

console.log(offset);