Blogger Ever

Progress on page scroll using Javascript

Show the user progress on scroll, quite helpful for magazine or tutorial sites.
Many famous news sites and blogs like The Daily Beast sows progress of how much content you've read on this page by showing the progress on the page. Usually the progress is shown in the form of bar or background colour progress. These bars or objects which shows the progress stay stick to the screen otherwise there is no use of it. It is quite easy to make with Javascript, have a look.
See the Pen Percentage of scroll by Mohammad Hamza Dhamiya (@hamzadhamiya) on CodePen.
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

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. 


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'); = percentage + '%';
showPer.innerHTML = Math.floor(percentage) + '%';
Hope you found it useful.

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.