Window scrollX property

Definition and Usage

scrollX property returns the number of pixels the document has scrolled from the top left corner of the window.

scrollX property is read-only.

Hint

scrollX property is equal to pageXOffset property.

For cross-browser compatibility, please use window.pageXOffset Instead of window.scrollX.

See also:

pageXOffset property

pageYOffset property

Example

Example 1

Scroll the content by 100 pixels and prompt scrollX and scrollY:

window.scrollBy(100, 100);
alert(window.scrollX + window.scrollY);

Try it yourself

Example 2

Create a sticky navigation bar:

// Get the navigation bar
const navbar = document.getElementById("navbar");
// Get the offset position of the navigation bar
const sticky = navbar.offsetTop;
// Add the sticky class to the navigation bar when you reach its scroll position. Remove the sticky class when leaving the scroll position.
function myFunction() {
  if (window.scrollY >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

Try it yourself

Syntax

window.scrollX

Or:

scrollX

Return value

Type Description
Number The number of pixels scrolling from the top left corner of the window.

Browser Support

All Browsers Support window.scrollX:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support