
Well, pen is enough for many of you that how stuff works. However, lets break it.
The first step is to make function and attach it on scroll event to document using addEventListener method.
function getHeight(){
// Function goes here
}
document.addEventListener('scroll',getHeight);
Next is to go for document height and window height. To get document height we use document.body.clientHeight and window.innerHeight for window height which returns height without scroll bars or tool bars. We subtract window height from document height to correct value when we are at top of page.
Then we need scroll height, which is actually the height which is scroll above in window. On every scroll this value changes and gives the change in percentage of the progress bar. document.body.scrollTop is used to get the scroll value of body.
Now all the values required are now in the hands, next is to get percentage from the document height with respect to scroll height. Just divide them and multiply it by 100 and we will the ratio based on 100.
percentage=(domScroll/domHeight)*100
Now lets put it on action using bar we've defined in markup and progress text node which shows the current percentage (round off).
bar = document.querySelector('.bar'),
showPer = document.querySelector('.percent');
bar.style.width = percentage + '%';
showPer.innerHTML = Math.floor(percentage) + '%';
Hope you found it useful.
Post A Comment:
0 comments: