Fade in on scroll
Mon Apr 11 2022 15:40:00 GMT+0000 (Coordinated Universal Time)
Saved by
@Kristi
#javascript
//HTML
<div class="container">
<div class="box box-1"></div>
<div class="box box-2"></div>
<div class="box box-3"></div>
<div class="box box-4"></div>
<div class="box box-5"></div>
</div>
//CSS
.container {
width: 100%;
display: flex;
flex-wrap: wrap;
}
.box {
width: calc(50% - 2rem);
height: 100px;
border-radius: 20px;
margin: 1rem;
transform: translateY(50px);
opacity: 0;
transition: all 0.5s;
}
.box-1 {
background-color: coral;
}
.box-2 {
background-color: cornflowerblue;
}
.box-3 {
background-color: palegoldenrod;
}
.box-4 {
background-color: violet;
}
.box-5 {
background-color: palegreen;
}
.inView {
opacity: 1;
transform: translateY(0px);
}
//Javascript
const boxes = document.querySelectorAll('.box');
window.addEventListener('scroll', fadeIn);
function fadeIn() {
boxes.forEach((box) => {
//get viewport-point where the transition should happen
let distanceInView =
box.getBoundingClientRect().top - window.innerHeight + 20;
if (distanceInView < 0) {
box.classList.add('inView');
} else {
box.classList.remove('inView');
}
});
}
//call function if elements are already on screen when pafge loads
fadeIn();
content_copyCOPY
https://codepen.io/bstonedev/pen/MWWZgKz
Comments