Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
passi9412

Toggle timeline (play/reverse) within another function of an ES6 class

Recommended Posts

Hi there,

 

I am very new to javascript and trying to keep the code readable. I want my timeline to be in a separate function and being played and reversed on a button click. However, the animation only fires forward, but never backwards and I cant get my head around it. If I put the timeline into the constructor method it suddenly works, but not if putting it into a separate function. The codepen is a very simplified version for the main issue. I'd glad if someone could lend me a helping hand. If you have better suggestions how to structure the code, I am very open to learn something. Just want to write it as clean as possible.

See the Pen eYZaQRM?editors=1111 by Passi9412 (@Passi9412) on CodePen

Link to comment
Share on other sites

Hey passi9412 and welcome to the GreenSock forums.

 

This is because variables in JavaScript are scoped to their respective functions. So if you want something that's created in one function to be accessible in other functions outside of it, you'll need to either 

  • Save it to a variable that is scoped outside of that function or
  • Return the variable so that it can be used outside of the function

So in your case it probably make sense to save the timeline to this.animation instead of const animation.

 

With that being said, your logic for opening and closing doesn't make too much sense to me. I think this makes more sense:

See the Pen oNxROBb?editors=0010 by GreenSock (@GreenSock) on CodePen

 

However, you're really just recreating a lot of what GSAP already does for you. Here's how I'd actually create it in a project. I talk more about this approach in my article about animating efficiently.

See the Pen wvGbZdy?editors=0010 by GreenSock (@GreenSock) on CodePen

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.
×