Search code examples
javascriptjquerycsstimeline.js

Timeline change css on enter view port


Am trying to change the background color of the timeline on scroll like on this site.My replication of the sample is development site. Take a look at the codepen I tried using. The closest I have come to replicating it is with the code below which makes the change in color on each timeline circle flicker on/off on scroll.

jQuery(document).ready(function($) {
function onScroll() {
  $('.cd-timeline-block').each( function() {
    if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.05 && $(this).find('.cd-timeline-img').hasClass('cd-inactive') ) {
      $(this).find('.cd-timeline-img').removeClass('cd-inactive').addClass('cd-active');
      $(this).find('.cd-date').addClass('cd-ssf-color');
    } else {
      $(this).find('.cd-timeline-img').addClass('cd-inactive').removeClass('cd-active');
      $(this).find('.cd-date').removeClass('cd-ssf-color');
    }
  });
};

$(window).scroll(onScroll);
});

Solution

  • I have made some modification to the above code.

    CodePen link: http://codepen.io/anon/pen/KzqWVm

    Javascript:

    jQuery(document).ready(function($) {
      var $timeline_block = $('.cd-timeline-block');
      var firstelm = $timeline_block.first();
    
        //on scolling, show/animate timeline blocks when enter the viewport
        $(window).on('scroll', function() {
          var _win = $(window), iselm = null;
          $timeline_block.each(function(index) {
            var _this = $(this);
            if (((_this.offset().top - _win.height())) <= (_win.scrollTop())) {
              iselm = _this;
            }
    
          });
          if (_win.scrollTop() < $(firstelm).offset().top) {
            iselm = $(firstelm);
          }
    
          if (iselm) {
            $('.cd-active').removeClass('cd-active').addClass('cd-inactive');
              iselm.find('.cd-timeline-img').removeClass('cd-inactive').addClass('cd-active');
    
            if ((iselm.offset().top - _win.height()) > (_win.scrollTop() * 0.75)) {
              $('.cd-date').removeClass('cd-ssf-color');
            }
            iselm.find('.cd-date').addClass('cd-ssf-color');
          }
        });
      });
    

    Continuing each loop on scroll might not work properly.