Skip to content Skip to sidebar Skip to footer

Trigger A Css Animation When The User Scrolls To Page Section

I have a simple CSS animation on my site, where I want to show 5 divs showing one at a time in a row. Everything works fine, but I want to make a trigger to that animation, when th

Solution 1:

You need JavaScript to do this.

In the example(s) below, a scroll event listener to attached, and the animate class is added to the #container element if the img elements are visible:

Updated Example

#container.animateimg {
  animation: animation .5s forwards;
}
document.addEventListener('scroll', function (e) {
  var top  = window.pageYOffset + window.innerHeight,
      isVisible = top > document.querySelector('#container > img').offsetTop;

   if (isVisible) {
     document.getElementById('container').classList.add('animate');
   }
});

Alternatively, you could also use jQuery as well:

Updated Example

$(window).on('scroll', function (e) {
   var top = $(window).scrollTop() + $(window).height(),
       isVisible = top > $('#container img').offset().top;

   $('#container').toggleClass('animate', isVisible);
});

Post a Comment for "Trigger A Css Animation When The User Scrolls To Page Section"