Search code examples
javascriptscrollmagicgsap

Trigger multiple elements with ScrollMagic with one scene


I'm using ScrollMagic to fade in an element as soon as it enters the screen, this works great but only works for the first element but the rest of the elements are not triggered. I'd like every element to be triggered and just use one scene to do this.

const controller = new ScrollMagic.Controller();

var scenefadein = new ScrollMagic.Scene({
	triggerElement: ".fade-in",
	triggerHook: 1,
	offset: 0,
  reverse: true
})
.setClassToggle(".fade-in", "visible")
.addTo(controller);
.spacing {
  padding-top:100px;
  padding-bottom:100px;
  border-bottom:1px solid #ececec;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.js"></script>

<div class="spacing"></div>

<div class="spacing">  
  <div class="fade-in">
    <img src="https://picsum.photos/200/300">
  </div>
</div>

<div class="spacing"></div>

<div class="spacing">  
  <div class="fade-in">
    <img src="https://picsum.photos/200/300">
  </div>
</div>

<div class="spacing"></div>


Solution

  • I found a solution using TweenMax and jQuery.

    var controller = new ScrollMagic.Controller();
    
    // loop through all elements
    $('.fade-in').each(function() {
      
      // build a tween
      var tween = TweenMax.from($(this), 0.7, {autoAlpha: 0, y: '+=200', x: '0', ease:Linear.easeNone});
    
      // build a scene
      var scene = new ScrollMagic.Scene({
        triggerElement: this,
    	triggerHook: 0.7,
    	offset: 0,
      reverse: true
      })
      .setTween(tween)
      .addTo(controller);
      
    });
    .spacing {
      padding-top:100px;
      padding-bottom:100px;
      border-bottom:1px solid #ececec;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/ScrollMagic.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.7/plugins/animation.gsap.js"></script>
    
    
    
    <div class="spacing"></div>
    
    <div class="spacing">
      <div class="fade-in">
        <img src="https://picsum.photos/200/300">
      </div>
    </div>
    
    <div class="spacing"></div>
    
    <div class="spacing">
      <div class="fade-in">
        <img src="https://picsum.photos/200/300">
      </div>
    </div>
    
    <div class="spacing"></div>