Skip to content

Instantly share code, notes, and snippets.

@maticrivo
Last active September 12, 2017 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maticrivo/6231922 to your computer and use it in GitHub Desktop.
Save maticrivo/6231922 to your computer and use it in GitHub Desktop.
Creates a reading indicator
(function(){
var Indicator = function(){
var self = this, bar, latestKnownScrollY, ticking;
this.init = function init() {
latestKnownScrollY = window.scrollY;
ticking = false;
self.createIndicator();
window.addEventListener('scroll', self.onScroll, false);
self.onScroll();
};
this.createIndicator = function createIndicator() {
bar = document.createElement('div');
bar.style.position = "fixed";
bar.style.top = 0;
bar.style.left = 0;
bar.style.right = 0;
bar.style.display = "block";
bar.style.width = "0%";
bar.style.height = "1px";
bar.style.backgroundColor = "#ff0000";
bar.style.zIndex = 99999999;
bar.style.WebkitTransition = 'all 0.5s';
bar.style.MozTransition = 'all 0.5s';
document.body.appendChild(bar);
};
this.onScroll = function onScroll(e) {
var percentage = Math.floor(((getScrollPosition() + getWindowHeight()) / getMaxDocumentHeight()) * 100),
color = (percentage >= 95) ? "#0000ff" : "#ff0000";
bar.style.width = percentage + "%";
bar.style.backgroundColor = color;
};
function getWindowHeight() {
return window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight
|| 0;
}
function getMaxDocumentHeight() {
return Math.max(
document.body.scrollHeight || 0
,document.documentElement.scrollHeight || 0
,document.body.offsetHeight || 0
,document.documentElement.offsetHeight || 0
,document.body.clientHeight || 0
,document.documentElement.clientHeight || 0
);
}
function getScrollPosition() {
return window.pageYOffset
|| document.body.scrollTop
|| document.documentElement.scrollTop
|| 0;
}
self.init();
};
new Indicator();
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment