So I have an "active" tag that is set to be added to elements with the class "reveal" when they are in the viewport. But after I scroll down the class "active" is now removed. How do I make it so that when "active" is first applied it does not get removed again. Below is the JavaScript that adds the "active" class.
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 = 20;
if (elementTop < windowHeight - elementVisible) {
reveals[i].classList.add("active");
}
else {
reveals[i].classList.remove("active");
}
}
}
window.addEventListener("scroll", reveal);
CodePudding user response:
Welcome to StackOverflow. You are using if else condition which is not required here. Just using a if block inside loop will do the work. Please see below code:
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 = 20;
if (elementTop < windowHeight - elementVisible) {
reveals[i].classList.add("active");
}
/*
Not needed
else {
reveals[i].classList.remove("active");
}
*/
}
}
window.addEventListener("scroll", reveal);
I have commented else block so it is not executed. Thanks!