JSFiddle - React, Tailwind, and code Playground
by nate
HTML
<div id="visible"></div>
<div id="element"></div>
CSS
body {
padding: 600px 200px;
height: 1200px;
}
#visible {
padding: 5px;
position: fixed;
top: 0;
left: 0;
}
#element {
background-color: red;
height: 300px;
width: 200px;
}
JavaScript
const element = document.getElementById("element");
const visible = document.getElementById("visible");
const logPercentageSeen = () => {
console.log(percentageSeen());
visible.textContent = `${percentageSeen()} %`;
};
window.addEventListener("scroll", logPercentageSeen);
const percentageSeen = () => {
// Get the relevant measurements and positions
const viewportHeight = window.innerHeight;
const scrollPosition = window.scrollY;
// Calculate percentage of the element that's been seen
const distance = scrollPosition + viewportHeight - element.offsetTop;
const percentage = Math.round(
distance / ((viewportHeight + element.offsetHeight) / 100)
);
// Restrict the range to between 0 and 100
return Math.min(100, Math.max(0, percentage));
};
// Log the initial value to the top before any scrolling has happened
logPercentageSeen();