I want my element appear via keyframe animation if they are visible on current window viewport.
Its kinda half working but my classList.remove('current') overrides my classList.add('current') so the behavior while scrolling isnt that smooth.
My Code
CSS
section.section{
&.current{
animation:expand 1s ease-in-out;
}
}
@keyframes expand {
from {
transform: scale(0);
display: block;
}
}
JS
const elements = document.querySelectorAll('section.section');
window.addEventListener('scroll', function (e) {
elements.forEach(el => {
let elTopPos = el.getBoundingClientRect().top + window.scrollY;
let elBottomPos = el.getBoundingClientRect().bottom + window.scrollY;
let windowBottomPos = window.innerHeight + window.pageYOffset;
let windowTopPos = window.scrollY;
if (el.classList.contains('current') === false) {
if ((windowBottomPos > elTopPos && windowBottomPos < elBottomPos) || (windowTopPos < elBottomPos && windowTopPos > elTopPos)) {
el.classList.add('current');
}
} else{
if ((windowTopPos > elBottomPos && windowBottomPos > elBottomPos) || (windowBottomPos < elTopPos && windowTopPos < elTopPos)) {
el.classList.remove('current');
}
}
})
},{
passive: true
})