Creating A Circular Reading Progress Indicator with jQuery and SVG

Creating A Circular Reading Progress Indicator with jQuery and SVG
File Size: 4.16 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A small jQuery plugin that draws an animated circular SVG progress bar with percentage to indicate the reading progress on your web page.

How to use it:

1. Create a circular progress bar using SVG element as follows.

<div class="progress">
  <div class="percent"></div>
  <svg class="progress-circle" width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMinYMin meet" class="svg-content">
  <path d="
      M50,1
      a49,49 0 0,1 0,98
      a49,49 0 0,1 0,-98
      "/>
  </svg> 
</div>

2. The required CSS to style the reading progress indicator.

.progress {
  position: fixed;
  right: 10px;
  top: 10px;
  height: 100px;
  width: 100px;
}

.progress .percent {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: rgba(0, 0, 0, 0.1);
  position: absolute;
  line-height: 100px;
  width: 100%;
}

.progress svg path { fill: none; }

.progress svg.progress-circle path {
  stroke: rgba(255, 0, 0, 0.55);
  stroke-width: 2;
}

3. Include the necessary jQuery javascript library at the bottom of the web page.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

4. Setup SVG animation.

var progressPath = document.querySelector('.progress path');
var pathLength = progressPath.getTotalLength();
progressPath.style.transition = progressPath.style.WebkitTransition =
'none';
progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
progressPath.style.strokeDashoffset = pathLength;
progressPath.getBoundingClientRect();
progressPath.style.transition = progressPath.style.WebkitTransition =
'stroke-dashoffset 300ms linear';

5. Define updateProgress function.

var updateProgress = function () {
// calculate values
var scroll = $(window).scrollTop();
var height = $(document).height() - $(window).height();
var percent = Math.round(scroll * 100 / height);
var progress = pathLength - (scroll * pathLength / height);
// update dashOffset
progressPath.style.strokeDashoffset = progress;
// update progress count
$('.percent').text(percent+"%");
}

6. Trigger updateProgress once on load and then on scroll.

updateProgress();
$(window).scroll(updateProgress);

This awesome jQuery plugin is developed by SachaG. For more Advanced Usages, please check the demo page or visit the official website.