I have a very simple function, that waits until a section is "within view" of the viewport. I'm wanting to animate/"grow" the section from something like .75 of it's natural size, to 1.
When I do this, the calculation often stops at say, 0.975 or something, leaving a very small (but very annoying) gap.
Also—it looks a little jittery, and I've tried to use requestAnimationFrame to negate any performance issues, but it still doesn't look great.
const CaseStudyGrow = () => {
let ticking = false;
let case_studies = document.querySelectorAll('.case_studies');
if (Object.values(case_studies).length <= 0) {
return;
}
const animate = () => {
let scroll = Math.round(window.scrollY);
let vh = Math.round(window.innerHeight);
Object.values(case_studies).forEach(casestudy => {
let offset = Math.round(casestudy.offsetTop);
// calc 3/4s of the viewport, to animate the scroll when the section is within a quarter of the viewport from being in view.
let q = vh / 4;
let grace = q * 3;
let target = parseInt(offset) - parseInt(grace);
if (((scroll + vh) - offset) > target) {
let grow = ((scroll + (vh + vh / 2)) - offset) / 1000;
grow = grow.toFixed(5);
if ((grow >= 0.75) && (grow <= 1)) {
casestudy.style.setProperty('--grow', grow);
}
}
// else {
// casestudy.style.setProperty('--grow', '0.75');
// }
});
};
document.addEventListener('scroll', () => {
requestAnimationFrame(animate);
}, false);
};
document.addEventListener('DOMContentLoaded', CaseStudyGrow, false);
Lastly, if you scroll really quickly up and down, the calculation is nowhere near, often stopping around 0.8 or something.
I'm definitely not doing this correctly but I need a solution.
Any help hugely appreciated.
Matt
Tried using Math.ceil / Math.round to get full values.
Tried using requestAnimationFrame to smooth performance.