Search code examples
javascriptgsap

JavaScript Greensock loop not working as expected


Does anyone have any ideas why this is not working? Seems to hit the first background but then does not change position.

// Avatar animations
var fadePulse           = true; // true: will fade avatar images and pulse in and out once changed
                                // false: will slide the avatars in and out 
var avatarCount         = 5;    // set the amount of avatars in the sprite image
var avatarSpeed         = 2     // set the avatar transition speed
var avatarHeight        = 250;  // set the height of a single avatar image
var avatars             = creative.avatars;
var animDuration        = 0.4;
var avatarCurrentIndex  = 0;

var avatarAni = new TimelineLite({ paused: true, repeat: -1 }); 

function startAvatarAnimation() {
    show(avatars);
    avatarAni.to(avatars, animDuration, {
        scaleX: 1, // 1.1 (for bouncing)
        scaleY: 1, // 1.1 (for bouncing)
        ease: Power3.easeIn,
        onComplete: onCompleteScaleIn
    });
    avatarAni.to(avatars, animDuration, {
        scaleX: 1,
        scaleY: 1,
        ease: Power3.easeOut
    });
    avatarAni.timeScale(avatarSpeed);
    avatarAni.play();
}

function onCompleteScaleIn() {
    avatarCurrentIndex ++;

    console.log(avatarCurrentIndex ++);
    if(avatarCurrentIndex <= avatarCount-1){ 
        TweenLite.set(avatars, {
            backgroundPosition: '0 -' + (avatarCurrentIndex * avatarHeight) + 'px'
        });
    } else { 
        avatarAni.pause();
        hide(avatars);
    }
}

It all seems to work apart from that part with looping through and adjusting the position.


Solution

  • // Avatar animations
    var fadePulse           = true; // true: will fade avatar images and pulse in and out once changed
                                    // false: will slide the avatars in and out 
    var avatarCount         = 5;    // set the amount of avatars in the sprite image
    var avatarSpeed         = 2     // set the avatar transition speed
    var avatarHeight        = 250;  // set the height of a single avatar image
    var avatars             = creative.avatars;
    var animDuration        = 0.4;
    var avatarCurrentIndex  = 0;
    var i = 0;
    
    var avatarAni = new TimelineMax({ paused: true, repeat: -1 });
    
    function startAvatarAnimation() {
        show(creative.avatars);
    
        avatarAni.to(avatars, animDuration, { scaleX: 1, scaleY: 1, ease: Power3.easeIn, onComplete: onCompleteScaleIn });
        avatarAni.to(avatars, animDuration, { scaleX: 1, scaleY: 1, ease: Power3.easeOut });
    
        avatarAni.timeScale(avatarSpeed);
        avatarAni.play();
    }
    
    function onCompleteScaleIn() {
        i++;
    
        if(i <= avatarCount-1){ 
            TweenMax.set(avatars, { backgroundPosition: '0 -' + (i * avatarHeight) + 'px' });
        } else { 
            avatarAni.pause();
            hide(avatars);
        }
    }