body {
padding: 0;
margin: 0;
font-family: "Josefin Sans", sans-serif;
}
section {
padding: 0;
margin: 0;
height: 500px;
width: 100%;
transition: all 1s;
transition-delay: 0.4s;
}
section:nth-child(even) {
background: #999;
}
section.in-viewscn {
background: #db2853;
}
section.in-viewscn:nth-child(even) {
background: #121212;
}
section p {
padding: 40px;
margin: 0;
font-size: 30px;
text-align: center;
}
const inViewport = (elem) => {
let allElements = document.querySelectorAll('.cmn-scn');
let windowHeight = window.innerHeight;
const elems = () => {
for (let i = 0; i < allElements.length; i++) { // loop through the sections
let viewportOffset = allElements[i].getBoundingClientRect(); // returns the size of an element and its position relative to the viewport
let top = viewportOffset.top; // get the offset top
if(top < windowHeight){ // if the top offset is less than the window height
allElements[i].classList.add('in-viewscn'); // add the class
} else{
//allElements[i].classList.remove('in-viewscn'); // remove the class
}
}
}
elems();
window.addEventListener('scroll', elems);
}
inViewport(); // run the function on all section elements