Monday, May 20, 2024
79
rated 0 times [  86] [ 7]  / answers: 1 / hits: 72249  / 15 Years ago, fri, march 5, 2010, 12:00:00

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?


More From » cross-browser

 Answers
16

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>




[#97415] Tuesday, March 2, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyasiaalmap

Total Points: 294
Total Questions: 107
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;