Skip to content

Instantly share code, notes, and snippets.

@DavidMellul
Last active June 13, 2018 13:42
Show Gist options
  • Save DavidMellul/a40fc3a8e786d046ee0817630bf2fc1d to your computer and use it in GitHub Desktop.
Save DavidMellul/a40fc3a8e786d046ee0817630bf2fc1d to your computer and use it in GitHub Desktop.
// The function that will take care of everything
function updateProgressBar() {
// Retrieve nodes & Scroll value
const progressBar = document.querySelector(".progress-bar");
const content = document.querySelector(".very-long-content");
const scroll = window.pageYOffset;
// Compute bottom part of the long content
const endPosition = content.offsetTop + content.offsetHeight - window.innerHeight;
// Compute percent on a 0-100 scale
const progress = Math.min(Math.ceil( (scroll / endPosition) * 100), 100);
// Update progress bar
progressBar.style.width = `${progress}%`;
}
window.onload = function() {
// If user has scrolled before the page has fully loaded, update the progress bar to ensure consistence
updateProgressBar();
// On scroll, update the progress bar
document.addEventListener('scroll', updateProgressBar);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment