Search code examples
javascriptcross-browserscroll

Cross-Browser Method to Determine Vertical Scroll Percentage in Javascript


How can I find out what percentage of the vertical scrollbar a user has moved through at any given point?

It's easy enough to trap the onscroll event to fire when the user scrolls down the page, but how do I find out within that event how far they have scrolled? In this case, the percentage particularly is what's important. I'm not particularly worried about a solution for IE6.

Do any of the major frameworks (Dojo, jQuery, Prototype, Mootools) expose this in a simple cross-browser compatible way?


Solution

  • Apr 2024 This solution will not quite get to 100% on modern mobile browsers, probably related to browser UI autohide-on-scroll behaviour

    Chrome, Firefox, IE9+. Live Demo on jsbin

    var h = document.documentElement, 
        b = document.body,
        st = 'scrollTop',
        sh = 'scrollHeight';
    
    var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
    

    As function:

    function getScrollPercent() {
        var h = document.documentElement, 
            b = document.body,
            st = 'scrollTop',
            sh = 'scrollHeight';
        return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
    }
    

    If you prefer jQuery (original answer):

    $(window).on('scroll', function(){
      var s = $(window).scrollTop(),
          d = $(document).height(),
          c = $(window).height();
    
      var scrollPercent = (s / (d - c)) * 100;
      
      console.clear();
      console.log(scrollPercent);
    })
    html{ height:100%; }
    body{ height:300%; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>