To get the current scrolling ratio, you should check if your document has a scrollableHeight first. In this special case I choosed to return 0
.
Next calculation is the same as above.
/**
* @returns number
*/
function scrollYProgression() {
const scrollableHeight = window.document.body.scrollHeight - window.innerHeight;
if (scrollableHeight <= 0) return 0;
return window.scrollY / scrollableHeight;
}
Bundled up with jQuery:
$(window).scroll(() => {
$('#progressbar')
.attr('value', scrollYProgression() * 100);
});
Beware when you listen to scroll events! This can be really heavy and you really need it at most once per repaint. You can check the window.requestAnimationFrame
to prevent massive call to your method (max 60/s).
Regarding scroll event listeners: http://www.html5rocks.com/en/tutorials/speed/animations
EDIT:
Without jQuery and using window.requestAnimationFrame
to limite trigger rate to 60/s
/** @return number */
function scrollYProgression() {
const scrollableHeight = window.document.body.scrollHeight - window.innerHeight;
if (scrollableHeight <= 0) return 0;
return window.scrollY / scrollableHeight;
}
/**
* @return void
* @description DOM element manipulation
*/
function scrollHandler() {
const progress = scrollYProgression();
const bar = document.getElementById('progressbar');
bar.setAttribute('value', progress * 100);
}
/** Start listening */
window.addEventListener('scroll', function(ev){
window.requestAnimationFrame(scrollHandler);
}, { passive: true });