Search code examples
javascriptanimationscrollmagic

trigger multiple elements using tween using same class


i will be using multiple svg lines for this and would basically need this code to be able to use the same trigger class for 5 svg lines. Just not sure how i would go about doing this. any help would be appreciated. hope this make sense..

<div id="trigger1"></div>
  <svg height="550" width="500">
  <line class="draw" x1="0" y1="0" x2="0" y2="100%" 
   style="stroke:rgb(128,128,128);stroke-width:2" />
</svg>

function pathPrepare ($el) {
    var lineLength = $el[0].getTotalLength();
    $el.css("stroke-dasharray", lineLength);
    $el.css("stroke-dashoffset", lineLength);
}

var $draw = $("line.draw");

// prepare SVG
pathPrepare($draw);
// build tween
var tween = new TimelineMax()
    .add(TweenMax.to($draw, 0.9, {strokeDashoffset: 0, ease:Linear.easeNone})) // draw word for 0.9


// build scene
var scene = new ScrollMagic.Scene({triggerElement: '#trigger1', duration: 500, tweenChanges: true})
                .setTween(tween)
                .addIndicators() 
                .addTo(controller);

Solution

  • If you just want to remove duplication you can do this

    $(".trigger").each(function(){      
        var $draw = $(this).find("line.draw");
        pathPrepare($draw); 
        // build tween
    var tween = new TimelineMax()
        .add(TweenMax.to($draw, 0.9, {strokeDashoffset: 0, ease:Linear.easeNone})) // draw word for 0.9
    
        new ScrollMagic.Scene({triggerElement: $(this)[0], duration: 500, tweenChanges: true})
                    .setTween(tween)
                    .addIndicators() 
                    .addTo(controller);
    
    })
    

    Assuming I have markup like this

    <div id="trigger1" class="trigger">
    
        <svg height="550" width="500">
      <line class="draw" x1="0" y1="0" x2="0" y2="100%" 
       style="stroke:rgb(128,128,128);stroke-width:2" />
    </svg>
    
    </div>
    
    <div id="trigger2" class="trigger">
    
        <svg height="550" width="500">
      <line class="draw" x1="0" y1="0" x2="0" y2="100%" 
       style="stroke:rgb(128,128,128);stroke-width:2" />
    </svg>
    
    </div>
    <div id="trigger3" class="trigger">
    
        <svg height="550" width="500">
      <line class="draw" x1="0" y1="0" x2="0" y2="100%" 
       style="stroke:rgb(128,128,128);stroke-width:2" />
    </svg>
    
    </div>
    

    Hope this helps. But you can only go to a certain extent like this if you want to control the directions of the line then you might need to edit the pathPrepare function based on the trigger section.

    https://codepen.io/srajagop/pen/GaZbrW?editors=0010