Search code examples
jqueryscrolloffsetscrolltop

How can I control when a class is added to an element on scroll in jQuery


I am using the following javascript in order to add and remove a class when scrolling the page:

(function($) {
  $.fn.timeline = function() {
    var selectors = {
    id: $(this),
    item: $(this).find(".timeline-item"),
    activeClass: "timeline-item--active",
    img: ".timeline__img"
  };
  selectors.item.eq(0).addClass(selectors.activeClass);

  var itemLength = selectors.item.length;

  $(window).scroll(function() {
    var max, min;
    var pos = $(this).scrollTop();
    selectors.item.each(function(i) {
      min = $(this).offset().top;
      max = ($(this).height() + $(this).offset().top);
      if (i == itemLength - 2 && pos > min + $(this).height() / 2) {
        selectors.item.removeClass(selectors.activeClass);
        selectors.item.first().addClass(selectors.activeClass);
        selectors.item.last().addClass(selectors.activeClass);
      } else if (pos <= max - 40 && pos >= min) {
        selectors.item.removeClass(selectors.activeClass);
        $(this).addClass(selectors.activeClass);
      }

    });
  });
 }

 $("#timeline-1").timeline();

 })(jQuery);

I have put together the following jsfiddle: https://jsfiddle.net/gpzfhwfq/ what I am trying to achieve here is to add a class as soon as each element on this timeline comes into view. The elements are blurred and when scrolling when they come into view the blur should disappear almost instantly but on the jsfiddle above the elements remain blurred for quite a long time when already in view. How could I make it so that they become visible, without blur almost as instantly as they come into the viewport when scrolling?


Solution

  • The problem lies within the positioning and the "else if" statement. The active class should be removed for each item individualy an not all the items at once. And I changed the positioning a little bit:

        } else if (pos <= max && pos >= min - window.innerHeight + $(this).height()/2) {
            $(this).addClass(selectors.activeClass);
        } else{
            $(this).removeClass(selectors.activeClass);
        }