Search code examples
javascripthtmlscrollhorizontal-scrollingvertical-scrolling

Cross-browser: Detecting scroll position JS only


I have searched high and low for an answer for this question and I FINALLY found it. I am writing this to hopefully save a future programmer a lot of time and frustration.

Please comment below if you would like to see something added or have any questions and I will add it. This will become a more complete answer as people bring forth issues.


Solution

  • This is a solution to find/detect the scroll bar position on the three major browsers(IE, Chrome, Firefox). Let me know if you find a version of these browsers that will not work and I will edit this answer to include that info.

    Older versions of chrome:
    var scrollTop = document.body.scrollTop; //Chrome
    var scrollLeft = document.body.scrollLeft; //Chrome
    
    Chrome > v.78.0.3904.97 (That I know of)
    var scrollTop = window.scrollY; //Chrome
    var scrollLeft = window.scrollX; //Chrome
    
    Other Browsers:
    var otherScrollTop = document.documentElement.scrollTop; //IE & Firefox
    var otherScrollLeft = document.documentElement.scrollLeft; //IE & Firefox
    

    These variables will detect the scroll position for the whole page.

    As @Eloy Pineda Mentioned: You can write this more concisely with:

    var scrollTop = window.scrollY || document.body.scrollTop || document.documentElement.scrollTop;
    var scrollLeft = window.scrollX || document.body.scrollLeft || document.documentElement.scrollLeft;