Skip to content

Instantly share code, notes, and snippets.

@sibiraj-s
Last active June 23, 2020 19:54
Show Gist options
  • Save sibiraj-s/740e81449bdb28a9d969a158cb82b676 to your computer and use it in GitHub Desktop.
Save sibiraj-s/740e81449bdb28a9d969a158cb82b676 to your computer and use it in GitHub Desktop.
Vertical Scroll Percentage
// include jQuery for this script to work
// or
// replace with vannila javascript where needed
var d = document.documentElement, b = document.body;
var scrollTop = d.scrollTop || b.scrollTop;
var scrollHeight = d.scrollHeight || b.scrollHeight;
var h = document.documentElement,
b = document.body,
st = "scrollTop",
sh = "scrollHeight",
progress = document.querySelector(".progress-bar"),
scroll;
var setProgress = function () {
scroll = (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100;
if (scroll > 99.99) {
scroll = 100;
}
progress.style.setProperty("--scroll", scroll + "%");
};
document.addEventListener("scroll", function () {
setProgress();
});
$(document).ready(function () {
setProgress();
var css = document.createElement('style');
css.type = 'text/css';
var styles = '.progress-bar {'
+ 'background: linear-gradient(to right, red var(--scroll), transparent 0);'
+ 'position: fixed;'
+ 'width: 100%;'
+ 'height: 2px;'
+ 'top: 0;'
+ 'left: 0;'
+ 'z-index: 3;'
+ '}';
if (css.styleSheet) css.styleSheet.cssText = styles;
else css.appendChild(document.createTextNode(styles));
document.getElementsByTagName("head")[0].appendChild(css);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment