I'm trying to have a timeline be part of multiple timelines in greensock. I guess the what I need to happen is one element needs to animate in both cases but only on or the other needs to animate in each case.
Heres what I have so far
var tl1 = new TimelineMax()
tl1.to(document.getElementById("one"), 0.5, { x: 10 })
var tl2 = new TimelineMax({ paused: true })
tl2.add(tl1)
tl2.to(document.getElementById("two"), 0.5, { x: 10 })
var tl3 = new TimelineMax({ paused: true })
tl3.add(tl1)
tl3.to(document.getElementById("three"), 0.5, { x: 10 })
tl2.play()
#one, #two, #three {
width: 10px;
height: 10px;
}
#one {
background-color: hsl(0,70%,50%);
}
#two {
background-color: hsl(100,70%,50%);
}
#three {
background-color: hsl(200,70%,50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.18.5/TweenMax.min.js"></script>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
Maybe there is a better way to achieve this...
Thanks in advance
There are many ways to accomplish this, but let me first point out a few things:
If your goal is to have #one animate from x:0 to x:10 in both timelines, you don't have to create nested timelines and try to re-use things. Instead, you can just drop a simple fromTo() tween into both. Like:
tl2.fromTo("#one", 0.5, {x:0}, {x:10})
.fromTo("#two", 0.5, {x:0}, {x:10});
tl3.fromTo("#one", 0.5, {x:0}, {x:10})
.fromTo("#three", 0.5, {x:0}, {x:10});
If you do want to use timelines and nesting, you could still do it in a tricky way - you could create tl1 (the one you want to re-use) as initially paused, and then use the tweenFromTo() method to basically animate its playhead from both timelines. tweenFromTo() simply spits back a tween that controls the playhead, thus you can nest that tween inside another timeline (and create multiple tweens that are doing that same thing). Like:
tl2.add(tl1.tweenFromTo(0, tl1.duration()));
tl3.add(tl1.tweenFromTo(0, tl1.duration()));
Does that help?