How can I get the scrollbar position with JavaScript?

653,113

Solution 1

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.

Solution 2

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].

Solution 3

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]

Solution 4

It's like this :)

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

Solution 5

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.

Share:
653,113

Related videos on Youtube

Paul
Author by

Paul

Updated on May 10, 2022

Comments

  • Paul
    Paul about 2 years

    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?

  • Max Shawabkeh
    Max Shawabkeh about 14 years
    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.
  • Paul
    Paul about 14 years
    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
  • Jorge Orpinel Pérez
    Jorge Orpinel Pérez over 10 years
    document.body.scrollLeft is what I needed :)
  • user18490
    user18490 almost 10 years
    Showing how to use this function with an example would have been great.
  • Dinesh Rajan
    Dinesh Rajan over 9 years
    I guess you can use this lastscroll = getScroll(); window.scrollTo(lastscroll[0], lastscroll[1]);
  • xd6_
    xd6_ almost 9 years
    Works great but i changed the return to an object with x and y keys since that makes a little more sense to me.
  • Kahless
    Kahless about 8 years
    This is almost right. for var b you should be subtracting window.innerHeight not element.clientHeight.
  • Admin
    Admin about 8 years
    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?
  • Ravinder Payal
    Ravinder Payal about 8 years
    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)
  • maia
    maia over 7 years
    scrollTop only worked for me when I added brackets... $(".scrollBody").scrollTop()
  • Janis Jansen
    Janis Jansen almost 7 years
    If you are dealing with the 'window' Element, you may use window.scrollY instead of window.scrollTop
  • Davide Cannizzo
    Davide Cannizzo over 6 years
    Edited following @user18490 's comment.
  • Green
    Green over 6 years
    The scrollTop property isn't W3C standard
  • fzzfzzfzz
    fzzfzzfzz about 6 years
    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.
  • John Balvin Arias
    John Balvin Arias almost 6 years
    @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
  • Jonny
    Jonny over 5 years
    ReferenceError: Can't find variable: element
  • Ben
    Ben over 5 years
    @JohnBalvinArias talking about fetch, what's up on ie11 or even Edge ?
  • Ben
    Ben over 5 years
    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
  • John Balvin Arias
    John Balvin Arias over 5 years
    @Ben where do you get the fact ie is broadly used? also, if you want to support ie I would argue that is better JQuery because native xhr is little bit messy, in the other hand it's a waste of time being all the time worry about if ie supports something, at least for me I just try to use the most update apis, and see if at least it is supported in chrome and in firefox
  • Ian Steffy
    Ian Steffy about 4 years
    I don't recommend 'scrollTop'. It has known issues and often doesnt work. I am surprised to see how many people rely on this fickle command
  • Danial Dezfouli
    Danial Dezfouli about 4 years
    use document.body instead
  • Timo
    Timo over 3 years
    @DineshRajan calling getScroll() assumes that the function def. is getScroll=function(){} without the document. Do not know why but it works without it.
  • Stefan
    Stefan over 3 years
    Just to be clear this in this context is referred to window. scrollY is a property of window
  • hngr18
    hngr18 almost 3 years
    Thank you Old Sport!
  • BoundForGlory
    BoundForGlory over 2 years
    why isnt this the answer.? Good job mate
  • WorldOfEmre
    WorldOfEmre over 2 years
    that worked! thanks a lot!!!
  • Jacob C.
    Jacob C. over 2 years
    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.
  • Peter Mortensen
    Peter Mortensen about 2 years
    Thus the meme.
  • Peter Mortensen
    Peter Mortensen about 2 years
    Does the snippet actually work?
  • lemospy
    lemospy about 2 years
    it is not a snippet anymore. but you can test it in your console and see the result
  • Marian07
    Marian07 almost 2 years
    There is also node.scrollWidth