I have utilized a function on this JSFiddle to retrieve the percentage of an element visible within the viewport while scrolling. The function ensures that the percentage is capped at 100 once the user scrolls beyond the element:
// Tracking the percentage of section seen within the viewport
// Assigning target section to a variable
const element = document.getElementById('section--example');
// Calculating the percentage of section in viewport
const percentageSeen = () => {
// Obtaining necessary measurements and positions
const viewportHeight = window.innerHeight;
const scrollTop = window.scrollY;
const elementOffsetTop = element.offsetTop;
const elementHeight = element.offsetHeight;
// Calculating the percentage of the element seen
const distance = (scrollTop + viewportHeight) - elementOffsetTop;
const percentage = Math.round(distance / ((viewportHeight + elementHeight) / 100));
// Restricting range between 0 — 100
return Math.min(100, Math.max(0, percentage));
}
Subsequently, I am trying to utilize the value of percentageSeen
in the following function to animate an SVG path as the user scrolls:
// Retrieving a reference to the <path>
var path = document.querySelector('#path--example');
// Getting the length of the SVG path
var pathLength = path.getTotalLength();
// Creating dashes to match the length of the SVG path
path.style.strokeDasharray = pathLength + ' ' + pathLength;
// Initially offsetting dashes to hide the SVG entirely
path.style.strokeDashoffset = pathLength;
path.getBoundingClientRect();
// Animating the SVG on scroll
window.addEventListener('scroll', function(e) {
// Fetching the percentage seen
var scrollPercentage = percentageSeen;
// Calculating the length to offset the dashes
var drawLength = pathLength * scrollPercentage;
// Drawing in reverse
path.style.strokeDashoffset = pathLength - drawLength;
});
I've documented my progress in a JSFiddle here. While I can successfully log the visible percentage to the console, it appears that the value is not being accepted when used in the scroll function above. Additionally, I can reveal the SVG based on page height (as commented out in the JSFiddle), but struggle with representing it based on section height. Can anyone offer guidance on how to effectively incorporate the percentageSeen
variable into the scroll function?