Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and set the current web page scroll position?

People also ask

How do I get scroll position?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

How do I scroll to a specific position in HTML?

In order to achieve our goal our easiest way is to apply: window. scrollTo( value-x, value-y ); Here value-x is the pixel value of the width, where you wanna jump or scroll to.

How do I get horizontal scroll position?

You can use $('html, body'). scrollLeft() to get the horizontal scrolling position if you use jQuery.


You're looking for the document.documentElement.scrollTop property.


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.

To get the current position, you want:

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

You can set the current position to 1000px down the page like so:

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

Or, using jQuery (animate it while you're at it!):

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

Update 2021: browsers inconsistencies regarding X/Y scroll amount seem to have disappeared, but I still use the solution in this answer whenever I need to.

There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0 when using document.documentElement.scrollTop or jQuery's $(window).scrollTop().

However, it works consistently with:

// horizontal scrolling amount
window.pageXOffset

// vertical scrolling amount
window.pageYOffset

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

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