Brad Woods Digital Garden

Notes / JavaScript / Web API / Scroll percent

Scroll percent

Planted: 

Status: decay

Hits: 942

Intended Audience: Creative coders, Front-end developers

Scrolling is a fundamental UI interaction on a webpage, on any device. Calculating how far the user has scrolled can be useful for creating sophiscated UX (user experience). Below shows how.

How far the user has scrolled the page.

id="myTarget"

targetMetrics.height...
page
document.body.scrollHeight...
viewport
window.innerHeight...
window.scrollY...
targetMetrics.y...
window.addEventListener("scroll", () => {
const { scrollHeight } = document.body; ...............................
const { innerHeight } = window; .......................................
const { scrollY } = window; ...........................................
const scrollArea = scrollHeight - innerHeight; ........................
const scrollPercent = scrollY / scrollArea * 100; .....................
function clamp(value, min = 0, max = 1) {
return Math.min(Math.max(value, min), max);
}
window.addEventListener("scroll", () => {
const targetMetrics = document.querySelector("#myTarget").getBoundingClientRect();
const { innerHeight } = window; .........................................
const scrollY = targetMetrics.y * -1; ...................................
const scrollArea = targetMetrics.height - innerHeight; ..................
const scrollPercent = clamp(scrollY / scrollArea) * 100; ................
const scrollY = (targetMetrics.y - innerHeight) * -1; ...................
const scrollArea = targetHeight; ........................................
const scrollPercent = clamp(scrollY / scrollArea) * 100; ................
const scrollY = targetMetrics.y * -1; ...................................
const scrollArea = targetHeight; ........................................
const scrollPercent = clamp(scrollY / scrollArea) * 100; ................
const scrollY = (targetMetrics.y - innerHeight) * -1; ...................
const scrollArea = targetHeight + innerHeight; ..........................
const scrollPercent = clamp(scrollY / scrollArea) * 100; ................