✨scroll progress on body
browser ⟩ event ⟩ type ⟩ scroll ⟩ example ⟩ scroll progress on body
update the progress bar's width when body.onscroll. (body's height is fixed)
replit ⟩ scroll progress (1) , require -> Node+ext, Element+boxes
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(200);
// ⭐️ event handlers
// -------------------------------------------------------
// body.onscroll (⭐️ windown/html.onscroll also works❗)
body.addEventListener("scroll", () => {
const maxScroll = body.scrollBox.height - body.paddingBox.height; // Element+boxes
const currentScroll = body.scrollBox.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}`;
}, true); // ⭐️ capturing: true (important❗)
// -> see: https://ayase.moe/2018/11/20/scroll-event/
📁 CSS
html, body {
height: 300px;
overflow: scroll; /* ⭐️ 必須 html, body 兩者都設定才有效,不知為何? */
}
Last updated
Was this helpful?