scroll progress

browsereventtype ⟩ scroll ⟩ example ⟩ scroll progress

update the progress bar's width onscroll. (body's height is automatic)

const { log } = console

// ⭐️ import
import { $ } from './js/ext/Node_ext.js';             // Node+ext
import { viewport } from './js/ext/Element+boxes.js'; // Element+boxes
// --------------------------------------------------------------------

// elements
const html = document.documentElement;     // <HTML>
const body = document.body;                // <BODY>
const bar = $("#progress");                // Node + ext
const info = $("#info");
const content = $('#content');

content.textContent = "supercali fragilisti cexpiali docious ".repeat(500);

// ⭐️ event handlers
// -------------------------------------------------------

// window.onscroll
window.addEventListener("scroll", () => {
    // same as: `html.scrollHeight - innerHeight`
    const maxScroll = html.scrollBox.height - viewport.height; // Element+boxes
    const currentScroll = viewport.y;                          // Element+boxes
    const percent = (currentScroll / maxScroll) * 100;
    // update UI
    bar.style.width = `${percent}%`;
    bar.textContent = `${percent.toFixed(0)}%`;
    info.textContent = `scroll amout: ${currentScroll} / max: ${maxScroll}`;
});

Last updated