Change Progress Bar Value based on Scrolling
22,221
Solution 1
Working DEMO
Try this
$(window).scroll(function () {
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
scrollPercent = (s / (d-c)) * 100;
var position = scrollPercent;
$("#progressbar").attr('value', position);
});
Hope this helps, Thank you
Solution 2
The logic is like this
totalValue = (documentHeight - windowHeight);
currntValue = scrolledValue;
percentage = (currntValue/ totalValue ) * 100
$(document).ready(function () {
$(window).scroll(function () {
var s = $(this).scrollTop(),
d = $(document).height()-$(window).height(),
scrollPercent = (s / d)*100;
$("#progressbar").attr('value', scrollPercent);
});
});
Author by
hakarune
A web designer that used to do a lot of cool stuff, but went dormant for a few years and trying to play catch up. Been trying my had at seeng what I can do with just CSS3 and free hosts...
Updated on July 31, 2020Comments
-
hakarune almost 4 years
I would like to be able to make my progress bar increase, based on how far I've scrolled and how much is left.
I've tried this: jsFiddle and it doesn't seem to work, I based my script off someone's script that made a block move horizontally based on scroll %.
My code:
<progress id="progressbar" value="0" max="100"></progress> <br /> <br /> <br /> Lorem<br /> Ipsum<br /> Dolor<br /> . . . .
JS:
$(document).ready(function () { $(window).scroll(function () { var s = $(this).scrollTop(), d = $(document).height(), scrollPercent = (s / d); var position = (scrollPercent); $("#progressbar").progressbar('value', position); }); });
-
jsea over 10 yearsYou need to subtract the viewport height from the document height as such: jsfiddle.net/SombreErmine/PvVdq/66
-
MarsOne over 10 yearsYou need to try this on a actual page to see if it works the same as in the fiddle. Cheers!
-
hakarune over 10 yearsThanks, for some reason the fiddle worked, but when I added it actually to the page I'm working on nothing happened. Thanks a bunch for another method.
-
kaleazy over 10 yearsThis is amazing, sweet!
-
Prime_Coder over 7 yearsThis is really awesome. +1
-
Antoine over 6 yearsThis won't always work : if
document.body.scrollHeight
andwindow.innerHeight
are equal! It will returnNaN
(and should raise aDividedByZeroError
). You can not guaranteedocument.body.scrollHeight
>window.innerHeight
. -
Zach Saucier almost 6 yearsWhy include jQuery for something so simple? And why just link to using
requestAnimationFrame
instead of just implementing a version that uses it? -
Antoine almost 6 yearsYou are totally right, jQuery because the original question make use of it. I add an implementation with
requestAnimationFrame
to debounce call to handler. Thanks for your feedback