Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
majelbstoat Avatar asked Mar 05 '10 13:03

majelbstoat


People also ask

What method allows you to get the vertical position of the scroll bar for an element?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.

How do I check if JavaScript is scrolling?

To detect if a user is scrolling with JavaScript, we can watch for scroll events by adding event handlers. to add the userHasScrolled variable. Then we set the window. onscroll property to a function that runs when we scroll.

How do I know my scroll position?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.


1 Answers

Oct 2016: Fixed. Parentheses in jsbin demo were missing from answer. Oops.

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>
like image 179
Phil Ricketts Avatar answered Sep 20 '22 06:09

Phil Ricketts