Similar, but not exactly like this other question, I want to know the percentage of scroll "lifecycle" of any given div
inside a scrollable document.
In other words:
When the top edge of the
div
is aligned with the bottom edge of the visible viewport, it's 0%When the bottom edge of the
div
is aligned with the top edge of the visible viewport, it's 100%If the
div
is below the visible viewport, it always remains 0%If the
div
is above the visible viewport, it always remains 100%
I tried adapting the solution from that other question, as well as a plugin like this; however in both of these cases the percentage decreases once the div begins scrolling out of view at the top of the viewport, which is not what I want.
I've attempted to do the maths on my own in this JSFiddle, but haven't been very successful: https://jsfiddle.net/5h3tdmb4/
var pct = (window.scrollY + window.innerHeight <= target.offsetTop) ? 0 : (window.scrollY + window.innerHeight) / (target.offsetTop + target.offsetHeight - window.scrollY);
How can the above calculation be achieved in vanilla JavaScript?