How to trigger a css animation on scroll in html?

by filiberto , in category: HTML & CSS , 2 months ago

How to trigger a css animation on scroll in html?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 2 months ago

@filiberto 

To trigger a CSS animation on scroll in HTML, you can use JavaScript to add a class to an element when it comes into view. Here is an example:

  1. Add a CSS class with the desired animation properties:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
.animate {
  animation: slideInFromLeft 1s ease;
}

@keyframes slideInFromLeft {
  0% {
    transform: translateX(-100%);
    opacity: 0;
  }
  100% {
    transform: translateX(0);
    opacity: 1;
  }
}


  1. Add the HTML element with the animation class:
1
<div class="box">Animate on scroll</div>


  1. Use JavaScript to detect when the element comes into view and add the animation class:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const box = document.querySelector('.box');

window.addEventListener('scroll', () => {
  const scrollPosition = window.scrollY;
  const elementPosition = box.getBoundingClientRect().top;

  if (elementPosition < window.innerHeight - 100) { // 100 is the offset from the bottom of the viewport
    box.classList.add('animate');
  }
});


This code will add the 'animate' class to the element with the 'box' class when it comes within 100 pixels from the bottom of the viewport. You can adjust the offset value as needed to trigger the animation at a different scroll position.