340

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? What would some code look like?

1
  • 2
    The actual thumb?! Commented Aug 8, 2022 at 22:30

13 Answers 13

333

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.

Sign up to request clarification or add additional context in comments.

10 Comments

What browser are you using? Getting the body is done differently in different browsers (element and document.body were just examples). See howtocreate.co.uk/tutorials/javascript/browserwindow for details.
I got it to give me the correct value on Firefox 3.6 with window.pageYOffset, but can't get anything working on IE7. Tried window.pageYOffset, document.body.scrollTop, document.documentElement.scrollTop, element.scrollTop
scrollTop only worked for me when I added brackets... $(".scrollBody").scrollTop()
If you are dealing with the 'window' Element, you may use window.scrollY instead of window.scrollTop
I think scroll position isn't set on document.body in most modern browsers - it's usually set on document.documentElement now. See bugs.chromium.org/p/chromium/issues/detail?id=157855 for Chrome's transition.
|
204

I did this for a <div> on Chrome.

element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.

element.scrollHeight - is the pixels of the whole div.

element.clientHeight - is the pixels that you see in your browser.

var a = element.scrollTop;

will be the position.

var b = element.scrollHeight - element.clientHeight;

will be the maximum value for scrollTop.

var c = a / b;

will be the percent of scroll [from 0 to 1].

1 Comment

This is almost right. for var b you should be subtracting window.innerHeight not element.clientHeight.
80

It's like this :)

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});

2 Comments

Just to be clear this in this context is referred to window. scrollY is a property of window
So developer.mozilla.org (MDN) is incorrect to say that throttling is needed due to the rapidity of scroll events?
67
document.getScroll = function() {
    if (window.pageYOffset != undefined) {
        return [pageXOffset, pageYOffset];
    } else {
        var sx, sy, d = document,
            r = d.documentElement,
            b = d.body;
        sx = r.scrollLeft || b.scrollLeft || 0;
        sy = r.scrollTop || b.scrollTop || 0;
        return [sx, sy];
    }
}

returns an array with two integers- [scrollLeft, scrollTop]

6 Comments

Showing how to use this function with an example would have been great.
I guess you can use this lastscroll = getScroll(); window.scrollTo(lastscroll[0], lastscroll[1]);
Works great but i changed the return to an object with x and y keys since that makes a little more sense to me.
Edited following @user18490 's comment.
ReferenceError: Can't find variable: element
|
24

Answer for 2018:

The best way to do things like that is to use the Intersection Observer API.

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. Unfortunately, as the web has matured, the need for this kind of information has grown. Intersection information is needed for many reasons, such as:

  • Lazy-loading of images or other content as a page is scrolled.
  • Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
  • Reporting of visibility of advertisements in order to calculate ad revenues.
  • Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

Implementing intersection detection in the past involved event handlers and loops calling methods like Element.getBoundingClientRect() to build up the needed information for every element affected. Since all this code runs on the main thread, even one of these can cause performance problems. When a site is loaded with these tests, things can get downright ugly.

See the following code example:

var options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

var observer = new IntersectionObserver(callback, options);

var target = document.querySelector('#listItem');
observer.observe(target);

Most modern browsers support the IntersectionObserver, but you should use the polyfill for backward-compatibility.

1 Comment

It's an unfortunate weakness in SO that answers that are accepted as correct can become (through no fault of the answerer) wrong, but are stuck as accepted forever. The accepted answer has become entirely wrong now for the document.body case, since, as @fzzfzzfzz said in a comment to the accepted answer, "scroll position isn't set on document.body in most modern browsers - it's usually set on document.documentElement now. See bugs.chromium.org/p/chromium/issues/detail?id=157855 for Chrome's transition." Ideally this 2018 Intersection Observer API answer would be set as the new accepted answer.
23

If you care for the whole page, you can use this:

document.body.getBoundingClientRect().top

3 Comments

use document.body instead
Does the snippet actually work?
it is not a snippet anymore. but you can test it in your console and see the result
14

Snippets

The read-only scrollY property of the Window interface returns the number of pixels that the document is currently scrolled vertically.

window.addEventListener('scroll', function(){console.log(this.scrollY)})
html{height:5000px}

Shorter version using anonymous arrow function (ES6) and avoiding the use of this

window.addEventListener('scroll', () => console.log(scrollY))
html{height:5000px}

3 Comments

So throttling is not needed?
well not really, but it might be a good idea to add a throttling in case you are worried about performance.
The problem is that the usual implementation of throttling is incorrect: after it processes an event, it deliberately misses events. So the more often the events occur, the more likely the parameters at the time of last event will be incorrect. Throttling not easy to get right, and I have not yet seen a correct design.
4

Here is the other way to get the scroll position:

const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

Comments

2

If you are using jQuery there is a perfect function for you: .scrollTop()

doc here -> http://api.jquery.com/scrollTop/

note: you can use this function to retrieve OR set the position.

see also: http://api.jquery.com/?s=scroll

7 Comments

Why answer a question about JS with a library for JS, when it is completely possible and even convenient to do it in raw JS? You're just asking him to add additional load time as well as use up some storage for something completely unnecessary. Also, since when did javascript start meaning JQuery?
if you ask individually I never liked jQuery and i haven't answered this question but in Vanilla JS there are already answers given by other fellows then what's a problem if some one have added a tasty spice in this thread.(He already mentioned that if you are using jQuery)
@R01010010 it's because now days JQuery is useless and counterproductive, all features from JQuery are easy implemented with VanilaJS, also you become depended of what's inside JQuery, with new features avaible in VanillsaJS, you as programer,won't update, just as example, now days there is a new API in VanillaJS called fetch that replaced old XHR, if you just were in the world of JQuery will never see the benefits on fetch and continue using jQuery.ajax().My personal opinion is that people who continue using JQuery it's because they stopped learning. Also VanillaJS is faster vanilla-js.com
@JohnBalvinArias talking about fetch, what's up on ie11 or even Edge ?
Correct me if I'm wrong, but fetch does not properly work on "modern" ie, and ie is still broadly used. If I were using jquery, i'd hardly be encouraged to move on then
|
1

I think the following function can help to have scroll coordinate values:

const getScrollCoordinate = (el = window) => ({
  x: el.pageXOffset || el.scrollLeft,
  y: el.pageYOffset || el.scrollTop,
});

I got this idea from this answer with a little change.

Comments

0

Not sure why everyone has posted such convoluted answers. To get the current scroll position of the page you can use

window.scrollY;

If you want the scroll as a percentage of total page then you can do the math using the height of the body.

document.body.scrollHeight;

If you want to check if a particular element is in view. It is recommended to use the Intersection observer API.

2 Comments

So, no throttling is needed?
Throttling is not needed if you're just reading values. But if you still want to, you can implement that
0

I think this may be the easier way To get the current scroll position of a page or any scrollable element. The scrollHeight will return the scroll height, but I think that the scrollY will return the current scrollbar position. Using javascript to get the scrollbar position

let currentScrollPosition = window.scrollY;
console.log(currentScrollPosition);

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-1

when you scroll you get the div postion

when you click on the div, the scroll bar scroll 500 in the y axis

function getTagPosition(event) {
        
  let x = document.getElementById("hi").offsetLeft

  let y = document.getElementById("hi").offsetTop

  console.log("x", x, "y", y);
         
}

function scrollToPosition(position) {

  console.log("was here")

  document.getElementById("hi").scrollTo(0, position);
  
}
 <div id="hi" onscroll="getTagPosition()" onclick="scrollToPosition(500)" style="width: 100px; height: 100px; overflow-y: scroll;">
        
        div dsgdfgf
        div dsgdfgf
         div dsgdfgf



         div dsgdfgf

          div dsgdfgf
          div dsgdfgf
          div dsgdfgf
          div dsgdfgf
          div dsgdfgf

           div dsgdfgf
           div dsgdfgf
           div dsgdfgf

            div dsgdfgf
            div dsgdfgf

            div dsgdfgf



             div dsgdfgf
              div dsgdfgf
              div dsgdfgf
              div dsgdfgf

               div dsgdfgf
    
    </div>
    
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.