How to get scrollbar position with Javascript?

Paul picture Paul · Mar 20, 2010 · Viewed 511.5k times · Source

I'm trying to detect the position of the browser's scrollbar with JavaScript to decide where in the page the current view is. My guess is that I have to detect where the thumb on the track is, and then the height of the thumb as a percentage of the total height of the track. Am I over-complicating it, or does JavaScript offer an easier solution than that? Any ideas code-wise?

Answer

Max Shawabkeh picture Max Shawabkeh · Mar 20, 2010

You can use element.scrollTop and element.scrollLeft to get the vertical and horizontal offset, respectively, that has been scrolled. element can be document.body if you care about the whole page. You can compare it to element.offsetHeight and element.offsetWidth (again, element may be the body) if you need percentages.