Window scrollX
Example 1
Scroll the content by 100 pixels, and alert the scrollX and scrollY:
window.scrollBy(100, 100);
alert(window.scrollX + window.scrollY);
Try it Yourself »
More examples below.
Definition and Usage
The scrollX
property returns the pixels a
document has scrolled from the upper left corner of the window.
The scrollX
property is read-only.
Note
The scrollX
property is equal to the
pageXOffset
property.
For cross-browser compatibility, use window.pageXOffset instead of window.scrollX.
See Also:
Syntax
window.scrollX
or just:
scrollX
Return Value
Type | Description |
A number | The number of pixels the document has scrolled from the upper left corner of the window. |
More Examples
Create a sticky navigation bar:
// Get the navbar
const navbar = document.getElementById("navbar");
// Get the offset position of the navbar
const 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.scrollY >= sticky) {
navbar.classList.add("sticky")
}
else {
navbar.classList.remove("sticky");
}
}
Try it Yourself »
Browser Support
window.scrollX
is supported in all browsers:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |