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;
Are we missing something? Help us improve this article. Reach out to us.
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;
Are you looking for other code tips?
JS Nooby
Javascript connoisseur