THE WORLD'S LARGEST WEB DEVELOPER SITE

Window pageXOffset and pageYOffset Properties

❮ Window Object

Example

Scroll the content by 100 pixels, and alert the pageXOffset and pageYOffset:

window.scrollBy(100, 100);
alert(window.pageXOffset + window.pageYOffset);
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The pageXOffset and pageYOffset properties returns the pixels the current document has been scrolled from the upper left corner of the window, horizontally and vertically.

The pageXOffset and pageYOffset properties are equal to the scrollX and scrollY properties.

These properties are read-only.


Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
pageXOffset Yes 9.0 Yes Yes Yes
pageYOffset Yes 9.0 Yes Yes Yes

Note: For IE8 and earlier, you can use "document.documentElement.scrollLeft" and "document.documentElement.scrollTop" instead (See "More Examples" below).



Syntax

window.pageXOffset
window.pageYOffset

Technical Details

Return Value: A Number, representing the number of pixels that the document has already been scrolled from the upper left corner of the window, horizontally and vertically

More Examples

Example

A cross-browser solution (using scrollLeft and scrollTop for IE8 and earlier):

window.scrollBy(100, 100);

if (window.pageXOffset !== undefined) { // All browsers, except IE9 and earlier
    alert(window.pageXOffset + window.pageYOffset);
} else { // IE9 and earlier
    alert(document.documentElement.scrollLeft + document.documentElement.scrollTop);
}
Try it Yourself »

Example

Create a sticky navigation bar:

// Get the navbar
var navbar = document.getElementById("navbar");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
  if (window.pageYOffset  >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
Try it Yourself »

❮ Window Object