Coder Perfect

How can I retrieve and set the current scroll position of a web page?

Problem

What is the best way to acquire and set the current scroll position of a web page?

I have a long form that needs to be refreshed based on the actions and input of the user. When this happens, the page reloads from the very top, which is inconvenient for visitors because they must scroll down to the point where they were.

If I could capture the current scroll position (in a hidden input) before the page reloads, I could then set it back after it reloads.

Asked by xyz

Solution #1

You’re on the lookout for a specific paper. documentElement.scrollTop is a property that allows you to scroll to the top of the document.

Answered by SLaks

Solution #2

The currently accepted answer is incorrect – document.documentElement.scrollTop always returns 0 on Chrome. This is because WebKit uses body for keeping track of scrolling, whereas Firefox and IE use html.

You’ll need the following items to obtain the current position:

document.documentElement.scrollTop || document.body.scrollTop

You may achieve this by setting the current position to 1000px down the page:

document.documentElement.scrollTop = document.body.scrollTop = 1000;

):

$("html, body").animate({ scrollTop: "1000px" });

Answered by tobek

Solution #3

Update 2021: The X/Y scroll amount anomalies in browsers appear to have vanished, but I still use the approach in this answer whenever I need to.

The way browsers display the current window scrolling coordinates has various irregularities. When utilizing document in Google Chrome on Mac and iOS, it appears to always return 0. $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ (window). scrollTop().

It does, however, operate consistently with:

// horizontal scrolling amount
window.pageXOffset

// vertical scrolling amount
window.pageYOffset

Answered by gyo

Solution #4

I choose to use HTML5 for local storage… Before changing windows, all of my links call a procedure that sets this. location:

localStorage.topper = document.body.scrollTop;

This is in the body of each page’s onLoad:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }

Answered by AXE Labs

Solution #5

This will give you the scroll from top px value.

document.documentElement.scrollTop

Answered by Bhavik Khawale

Post is based on https://stackoverflow.com/questions/4096863/how-to-get-and-set-the-current-web-page-scroll-position