スクロールに応じて要素をアニメーション付きで表示させる

Ads

Result

jQuery

function Utils() {}
Utils.prototype = {
  constructor: Utils,
  isElementInView: function(element, fullyInView) {
    var pageTop = $(window).scrollTop();
    var pageBottom = pageTop + $(window).height();
    var elementTop = $(element).offset().top;
    var elementBottom = elementTop + $(element).height();

    if (fullyInView === true) {
      return pageTop < elementTop && pageBottom > elementBottom;
    } else {
      return elementTop <= pageBottom && elementBottom >= pageTop;
    }
  }
};

var Utils = new Utils();
$(window).on("load", addFadeIn());

$(window).scroll(function() {
  addFadeIn(true);
});

function addFadeIn(repeat) {
  var classToFadeIn = ".will-fadeIn";

  $(classToFadeIn).each(function(index) {
    var isElementInView = Utils.isElementInView($(this), false);
    if (isElementInView) {
      if (!$(this).hasClass("fadeInRight") && !$(this).hasClass("fadeInLeft")) {
        if (index % 2 == 0) $(this).addClass("fadeInRight");
        else $(this).addClass("fadeInLeft");
      }
    } else if (repeat) {
      $(this).removeClass("fadeInRight");
      $(this).removeClass("fadeInLeft");
    }
  });
}

css

.will-fadeIn {
  display: block;
  width: 100%;
  max-width: 640px;
  margin: 20px auto;
  height: 250px;
  background-color: #b7f7f7;
  padding: 10px;
}

.fadeInRight {
  animation: fadeInRight .5s ease .4s both;
}
@media (prefers-reduced-motion) {
  .fadeInRight .animated {
    animation: unset !important;
    transition: none !important;
  }
}

.fadeInLeft {
  animation: fadeInLeft .5s ease .4s both;
}
@media (prefers-reduced-motion) {
  .fadeInLeft .animated {
    animation: unset !important;
    transition: none !important;
  }
}



@keyframes fadeInRight {
  from {
    opacity: 0;
    transform: translate3d(100%, 0, 0);
  }
  to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}
@keyframes fadeInLeft {
  from {
    opacity: 0;
    transform: translate3d(-100%, 0, 0);
  }
  to {
    opacity: 1;
    transform: translate3d(0, 0, 0);
  }
}

html

<main>
<div class="will-fadeIn">
  <p>foo bar</p>
</div>
  <div class="will-fadeIn"></div>
  <div class="will-fadeIn"></div>
  <div class="will-fadeIn"></div>
  <div class="will-fadeIn"></div>
  <div class="will-fadeIn"></div>
  <div class="will-fadeIn"></div>
  <div class="will-fadeIn"></div>
</main>

via

show elements on scroll