Jump to content
Search Community

Get a timeline with Javascript

Robert May test
Moderator Tag

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

Recommended Posts

Thanks for the reply Shaun. The problem may be that I'm using a text variable "currentTimeline" + "Tl". This gets the name of the timeline and the console logs as "slde1Tl" as it should, but getElementById returns tempTimeline as "null".

 

console.log(currentTimeline + "Tl")

var tempTimeline = document.getElementById(currentTimeline + "Tl")
tempTimeline.pause();

Link to comment
Share on other sites

Hi @Robert May,

 

That's because Javascript doesn't accept variable variable names the way other languages do. For example, in PHP you can do the following

 

$foo = 'bar';

$$foo = 'baz';

echo $bar; // output would be 'baz'

echo ${$foo};  // output would also be 'baz'

 

In Javascript, variables are stored as properties of the window object. So the following illustrates how to use variable variable names in Javascript

 

 var tl0 = new TimelineMax({paused: true});
 var tl1 = new TimelineMax({paused: true});
 var tl2 = new TimelineMax({paused: true});
 var tl3 = new TimelineMax({paused: true});

for( var i=0; i<4; i++ ){
 	 console.log( window['tl'+i] ); // outputs the timeline objects
}

 

 

I assume in your example ...

 

console.log(currentTimeline + "Tl")
var tempTimeline = document.getElementById(currentTimeline + "Tl")
tempTimeline.pause();

 

... that `currentTimeline` simply refers to a string ... so console.log will simply concatenate and output what you expect, but that doesn't refer to any timeline. The way you are trying to reference the timeline is through an element selector, which won't work (that's looking for a DOM element). Timeline's are Javascript objects. So, as in the previous examples, the way to reference a Timeline is by its assigned variable name. 

 

Here is a codepen illustrating variable variables in Javascript and how to reference a timeline. Hope it helps!

 

See the Pen ZVbBae by sgorneau (@sgorneau) on CodePen

 

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...