Search code examples
javascriptgsapscrollmagic

How to target children in a each loop using GreenSock and ScrollMagic


I want to be able to have each div with the class of .fade-in target its children h1(slide in right) and span(slide in left) by using a each() loop. So my question is how do I target a child element using 'this' e.g tl.from('.fade-in h1', 1, {x: 300}) Replace .fade-in with "this"?

tl
  .from(
    ".fade-in h1",
    0.3,
    { autoAlpha: 0, scale: 0.5, x: 300, ease: Linear.easeNone },
    "x"
  )
  .from(
    ".fade-in span",
    0.3,
    { autoAlpha: 0, scale: 0.5, x: -300, color: "red", ease: Linear.easeNone },
    "x"
  );

Demo Link


Solution

  • Try this

    Check Demo Here

    // init controller
    var controller = new ScrollMagic.Controller();
    
    // loop through all elements
    $(".fade-in").each(function() {
      var jh1 = $(this).find("h1");
      var jspan = $(this).find("span");
      var tl = new TimelineMax();
    
      tl
        .from(
          jh1,
          0.5,
          { autoAlpha: 0, scale: 0.5, x: 300, ease: Linear.easeNone },
          "x"
        )
        .from(
          jspan,
          0.5,
          {
            autoAlpha: 0,
            scale: 0.5,
            x: -300,
            color: "red",
            ease: Linear.easeNone
          },
          "x"
        );
    
      // build a scene
      var scene = new ScrollMagic.Scene({
        triggerElement: this,
        offset: 10,
        triggerHook: 0
      })
        .setTween(tl) // trigger a TweenMax.to tween
        .addIndicators()
        .addTo(controller);
    });