How to get and set scroll position of the document using JavaScript

published: 04 May 2022

2 min read

Get and set scroll position of the document using JavaScript

To get the scroll position of the document, you can use the pageXOffset, pageYOffset properties of the window object or the scrollLeft and scrollTop properties of the documentElement object.

Here is an example:

const x = window.pageXOffset || document.documentElement.scrollLeft;
const y = scrollTop = window.pageYOffset || document.documentElement.scrollTop;

To reset the scroll position of the document, just update the documentElement and body's scrollLeft and scrollTop properties:

document.documentElement.scrollTop = document.body.scrollTop = 250;
document.documentElement.scrollLeft = document.body.scrollLeft = 300;

How to get and set scroll position of the document using JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming