Play with a custom progress scroll indicator code

25th January, 2018 - 3 min. read - in Tutorials - Go to Index

If you want to implement a progress scroll indicator, you have two options:

The latter is what I did that turned out simpler (from the amount of code perspective) than I thought at first instance. It has been also the opportunity to play with this specific behavior outside the initial goal.

First off, the code. A progress bar element might be a simple div that needs to be styled with CSS. With the following HTML and CSS we have now an element ready to be managed by javascript:

<div id="indicator"></div>
#indicator{
  position: fixed;
  top:0;
  left:0;
  height: 3px;
  background-color: red;
  z-index: 999;
}

If you add this CSS rule you’ll have a much more smooth animation. I do prefer the more straight width calculation, though.

transition: width .25s ease-in-out;

The next requirement is the logic part (I’m shamelessly using jQuery to write less code here):

$(window).on('scroll', function () {
  var scrollPos = $(window).scrollTop()
  var winHeight = $(window).height()
  var docHeight = $(document).height()
  var perc = 100 * scrollPos / (docHeight - winHeight)
  $('#indicator').width(perc + '%')
})

That’s it. With these code you’ll have a neat progress scroll indicator on your page:

See the Pen NXZdgq by Fabio Franchino (@abusedmedia) on CodePen.

You might notice that using percentage value means basically that the progress bar is fluid by design no matter the window width even if the user resizes the window at runtime.

As you might notice, the js function compute a perc value that can be used for anything in your page, let’s say, the background color:

See the Pen ppXRpN by Fabio Franchino (@abusedmedia) on CodePen.

Or using the powerful animation library TweenMax to control more complex animations using the TimelineMax component with this code:

var tl = new TimelineMax().pause()
tl.to('#a', 4, {y:100})
tl.to('#b', 4, {y:200})
...

$(window).on('scroll', function () {
  var scrollPos = $(window).scrollTop()
  var winHeight = $(window).height()
  var docHeight = $(document).height()
  var perc = scrollPos / (docHeight - winHeight)
  tl.progress(perc)
})

Where the Timeline progression will be handled by the perc value.

See the Pen LeKxMX by Fabio Franchino (@abusedmedia) on CodePen.

As you can see, endless possibilities.

Want to ask something? Drop me a line!

Not ready to talk? Follow me on Twitter.


Spotted a typo or (likely) a grammar error? Send a pull request.