Petit code qui permet de faire en sorte de faire avancer (ou reculer) une animation CSS en fonction du scroll.
.animate .animation {
animation: 1s linear;
animation-play-state: paused;
animation-delay: calc(0 * -1s);
animation-iteration-count: 1;
animation-fill-mode: both;
}
.animate.fadeIn .animation {
opacity: 0;
animation-name: fadeIn;
}
.animate.zommScrollImg .animation {
transform: scale(1);
animation-name: zommScrollImg;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes zommScrollImg {
to {
transform: scale(1.3);
}
}<script>
function elementInView(elem){
return elem.getBoundingClientRect().top > 0 && elem.getBoundingClientRect().top < window.innerHeight;
}
// L'animation se délenche quand le haut de l'élément est à 0% de la hauteur de la fenêtre et se termine quand le bas de l'élément atteint 50% de la hauteur de la fenêtre
function getScrollPercentage(element) {
const rect = element.getBoundingClientRect();
const viewportHeight = window.innerHeight;
if (rect.bottom <= viewportHeight * 0.5) {
return 1;
}
if (rect.top >= viewportHeight) {
return 0;
}
const distanceFromBottom = viewportHeight - rect.top;
const totalScrollableDistance = viewportHeight + rect.height - (viewportHeight * 0.5);
const percentage = distanceFromBottom / totalScrollableDistance;
return Math.min(1, Math.max(0, percentage));
}
const animate = document.querySelectorAll('.animate');
window.addEventListener('scroll', scrollAnimate);
function scrollAnimate() {
for(var i = 0; i < animate.length; i++) {
if( elementInView(animate[i]) ) {
let offsetY = animate[i].getBoundingClientRect().top + window.scrollY;
var stateAnimation = getScrollPercentage(animate[i]);
animate[i].querySelector(".animation").style.animationDelay = 'calc('+stateAnimation+' * -1s)';
}
}
}
</script>