JavaScript/jQuery add class when element comes into viewport?

后端 未结 2 2028
囚心锁ツ
囚心锁ツ 2021-01-20 23:34

Is there a way to add a class when the element that I want to apply the class to comes into the viewport? Or when the bottom of the screen is a certain distance past the top of

2条回答
  •  生来不讨喜
    2021-01-20 23:40

    You could do something like this: (See CodePen for implementation)

    Function taken from here: Check if element is visible after scrolling

    CodePen

    $(window).on('scroll', function() {
      $(".graph").each(function() {
        if (isScrolledIntoView($(this))) {
          $(this).find(".graph-line").addClass("graph-75");
          $(this).find(".graph-line-2").addClass("opacity");
        }
      });
    });
    
    function isScrolledIntoView(elem) {
      var docViewTop = $(window).scrollTop();
      var docViewBottom = docViewTop + $(window).height();
    
      var elemTop = $(elem).offset().top;
      var elemBottom = elemTop + $(elem).height();
    
      return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }
    

    Altough this is not perfect, it should point you into the right direction.

提交回复
热议问题