Hey guys my brain is afk right now so I am asking yall:
I am trying to make a reveal animation everytime the element is visible. At the moment this only works when you scroll down and make the element visible from the top. I want to extend this also for scrolling up and making the element visible from the bottom.
Can anyone please explain what I need to change in order to accomplish that?
JAVASCRIPT:
function reveal() {
var reveals = document.querySelectorAll(".reveal");
for (var i = 0; i < reveals.length; i++) {
var windowHeight = window.innerHeight;
var elementTop = reveals[i].getBoundingClientRect().top;
var elementVisible = 100;
var elementHidden = ;
if (elementTop < windowHeight - elementVisible) {
reveals[i].classList.add("active");
}
else {
reveals[i].classList.remove("active");
}
}
}
window.addEventListener("scroll", reveal);
reveal();
CSS:
.reveal{
transform: translateY(SOMEVALUEpx);
opacity: 0;
}
.reveal.active{
transform: translateY(0);
opacity: 1;
}
Add another check in your if statement to see if the element bottom has reached height 0 plus the elementVisible value.
function reveal() {
var reveals = document.querySelectorAll(".reveal");
var windowHeight = window.innerHeight;
var elementVisible = 100;
for (var i = 0; i < reveals.length; i++) {
var elementTop = reveals[i].getBoundingClientRect().top;
var elementBottom = reveals[i].getBoundingClientRect().bottom;
if (elementTop < windowHeight - elementVisible || elementBottom > 0 + elementVisible) {
reveals[i].classList.add("active");
} else {
reveals[i].classList.remove("active");
}
}
}
window.addEventListener("scroll", reveal);
reveal();
I also defined windowHeight and elementVisible outside the loop, as they don't need to be redefined for each iteration of the loop. All this happens in one single scroll.