Scroll percentPlanted: Mar 2024Status: decayPlanted: Mar 2024Hits: 942Intended Audience: Creative coders, Front-end developersScrolling 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.Page ScrollSection ScrollHow far the user has scrolled the page.From first pixel hits top of viewport until the last pixel hits bottom of viewportFrom first pixel enters viewport until the last pixel hits bottom of viewportFrom first pixel hits top of viewport until the last pixel exits viewportFrom first pixel enters viewport until the last pixel exits viewportid="myTarget"targetMetrics.height... pagedocument.body.scrollHeight... viewportwindow.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; ................