GSAP timeline various onComplete functions on different tweens
Sebastian Wright
First of all I'm new with GSAP and ScrollMagic, so forgive me if I might be asking a silly question here. I've been looking over the internet but didn't succeed in finding the right answer for my problem.
Anyways, I'm trying to create a timeline where on the complete of each 'to' function a call to an external function will be made with specific params.
var controller = new ScrollMagic.Controller();
var timeline = new TimelineLite();
var div = $('div');
timeline.to(div, 0.5, { opacity: 0, onComplete: toggleOverlay(0)
}, "part-1")
.to(div, 0.5, { opacity: 1, onComplete: toggleOverlay(1)
}, "part-2")
.to(div, 0.5, { opacity: 0, onComplete: toggleOverlay(2)
}, "part-3");
var scene = new ScrollMagic.Scene({ triggerElement: "#trigger-event", duration: 500
})
.setTween(timeline)
.addTo(controller);
function toggleOverlay(i){ console.log(i);
}What happens here: The timeline will be called once the scroll position reaches the '#trigger-event'. Subsequently, the '.to' functions will be called based on the scroll position after the trigger event and before the end (duration).
The problem I face here, is that the onComplete functions are called directly on the page load. This has probally something to do with the '.setTween(timeline)', as I can imagine it loads in the whole timeline.
What would be the solution for my problem or what would be an good alternative method?
EDIT: Here's a JSFiddle:
Thanks in regards, Enzio
1 Answer
You have invoked the functions immediately by using parenthesis (). Have a read of this answer to understand better the difference between assigning a function to a variable and actually executing it immediately.
In GSAP, the way to go about it would be to have triggerOverlay function assigned to onComplete without the parenthesis like so:
...
onComplete: toggleOverlay
...And to receive the additional parameters you have something called onCompleteParams to pass them to, as an array, like so:
...
onCompleteParams: [0]
...So your overall code should look like:
...
timeline.to(div, 0.5, { opacity: 0, onComplete: toggleOverlay, onCompleteParams: [0]
}, "part-1")
.to(div, 0.5, { opacity: 1, onComplete: toggleOverlay, onCompleteParams: [1]
}, "part-2")
.to(div, 0.5, { opacity: 0, onComplete: toggleOverlay, onCompleteParams: [2]
}, "part-3");
... 2