Animate objects depending on scroll position

Posted on

in

,

For any items on the page that you want to animate when scrolled to add a ‘data-scroll-class’ attribute with the string of what class you want to add to animate and an optional ‘data-scroll-delay’ attribute with the amount of delay you want in seconds. For example:

<div data-scroll-class="animate" data-scroll-delay="2"></div>

Then add this js

$(window).scroll(function() {
 var scrollAmt = parseInt($(window).scrollTop()+$(window).height() / 2);
               
 $('[data-scroll-class]').each(function(i, obj) {
                   
  var $el = $(this);
                   
  if(scrollAmt > $(this).offset().top){
   var scrollClass = $(this).attr("data-scroll-class");
   var thisDelay = $(this).attr("data-scroll-delay")*1000 || 0;
                       
   var addScrollClass = setTimeout(
    function(){
     $el.removeAttr("data-scroll-class");
     $el.addClass(scrollClass); 
    }, thisDelay);
   }
  }
 );
}

What’s happening is when you scroll to the middle of an element with the data-scroll-class attribute it will add the class of that’s specified in ‘data-scroll-class’ with a delay if that’s specified as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

December 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031