Categories
JavaScript Answers

How to Get and Set the Current Web Page Scroll Position with JavaScript?

Spread the love

Sometimes, we want to get and set the current web page scroll position with JavaScript.

In this article, we’ll look at how to get and set the current web page scroll position with JavaScript.

Get the Current Web Page Scroll Position

We can use the document.documentElement.scrollTop or document.body.scrollTop to get the scroll position of the page.

For instance, we can write:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  document.body.appendChild(p)
}

window.addEventListener('scroll', () => {
  console.log(document.documentElement.scrollTop, document.body.scrollTop)
});

to add elements to a div and listen to the scroll event on the window.

In the event listener, we log the document.documentElement.scrollTop property which should log the scroll position of the page.

As we scroll up or down, document.documentElement.scrollTop should change in value.

Set the Current Web Page Scroll Position

We can also set the document.documentElement.scrollTop property to the scroll position we want.

The position should be a number in pixels.

For instance, we can write:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  document.body.appendChild(p)
}

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

to set the document.documentElement.scrollTop and the document.body.scrollTop property to 300 pixels down the page.

Now we should see that the page is scrolled down 300 pixels.

Conclusion

We can get and set the scroll position of a page with the document.documentElement.scrollTop property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *