Quantcast
Channel: David Kelley » CodeDavid Kelley
Viewing all articles
Browse latest Browse all 7

Scrolling Progress Bar

$
0
0

This script looks at creating an animated progress bar that truly reflects the current scroll position on the web page. A seemingly simplistic feature that can be difficult to get right.

A while ago, I implemented a feature similar to this on the Piccsy Investor Pitchdeck, it is a simple aesthetic effect which provides no function at all; however, it sparked multiple Stackoverflow threads (some here and here) of people asking how the effect is achieved. Whilst the answers provided do achieve the desired effect – they are technically not accurate.

If you calculate the percentage of the document scrolled by only using the scrollY value, the progress bar will never completely fill, as the maximum value of scrollY can only ever be the height of the window subtracted from the height of the document itself. Alternatively, if you use the sum of scrollY + document.height, the minimum percentage of your progress bar will only ever be the proportional percentage-based value that the sum represents, never 0.

Lets take a look at a simple method of truly calculating the percentage of the page which has been scrolled…

progress-1

In the stunningly beautiful and highly detailed diagram above, represents the overall height of the webpage, whilst represents the current distance scrolled from the top of the page, ala scrollY.

progress-2

(Please forgive my awful naming of w, I was totally drunk whilst making these images…)

In the above diagram, we determine to be the height of the window. Using s, h and w, we can now determine the proportional value of window height, based upon the current percentage of the document that has been scrolled. will increase as the user scrolls down and will decrease as the user scrolls up. This value is used in conjunction with to determine the accurate percentage of the document that has been scrolled. Using a little help from jQuery, we can easily translate this into Javascript:

var s = $(window).scrollTop();
var h = $(document).height();
var w = $(window).height();

var t = (s / h) * w;

Now that has been calculated, we can use the formula in the diagram below to determine the correct percentage of the document scrolled.

progress-3

 

Pfft, nobody wants to see mathematical formulas.. lets transform this into Javascript:

var s = $(window).scrollTop();
var h = $(document).height();
var w = $(window).height();

var t = (s / h) * w;

//thats a bingo!
var p = ((s + t) / h) * 100 + 1

The only thing left to do now that has been calculated is to apply this percentage to the progress bar that you are using. I won’t go into actually animating the element in this post, but I have made a demonstration of the entire thing here.


Viewing all articles
Browse latest Browse all 7

Trending Articles