2

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:

  1. When the top edge of the div is aligned with the bottom edge of the visible viewport, it's 0%

  2. When the bottom edge of the div is aligned with the top edge of the visible viewport, it's 100%

  3. If the div is below the visible viewport, it always remains 0%

  4. 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?

Emphram Stavanger
  • 4,158
  • 9
  • 35
  • 63

1 Answers1

1

This should be it Jsfiddle... i just fixed the maths and changed how the pecentage was getting calculated :

document.addEventListener("scroll", function(){
var target = document.getElementById("target");
var itemLength = (window.scrollY + window.innerHeight) <= target.offsetTop 
  ? 0 
  : ((window.scrollY + window.innerHeight) - target.offsetTop) <= (window.innerHeight + target.offsetHeight)
  ? (window.scrollY + window.innerHeight - target.offsetTop)
  : (window.innerHeight + target.offsetHeight)

  var percentage = Math.round((itemLength * 100) / (window.innerHeight + target.offsetHeight))
  /* Show in DOM */
  document.getElementById("pct").innerHTML =  percentage + "%";
});
Abdelillah Aissani
  • 3,058
  • 2
  • 10
  • 25