Jump to content
Search Community

Play and Reverse buy clicking the same button

HomTom test
Moderator Tag

Recommended Posts

In my animation, I can start the animation by clicking on the Red button in the top right corner of the page.

But I also want to be able to reverse the animation by clicking a second time on the same button.

To achieve this I'm using this condition, but it's not working:

 

tl.reversed() ? tl.play() : tl.reverse()

This is the complete code:

 

const tl = gsap.timeline({ defaults: { duration: 1 } })

tl.from('.anim1', { stagger: 0.6, y: -50, opacity: 0 })
  .from('aside', { backgroundPosition: '200px 0px', opacity: 0 }, '-=1.5') // relative timing (-= means sooner)
  .from('img', { y: 30, opacity: 0 }, '-=0.5')

const playBtn = document.getElementById('play-btn')

playBtn.addEventListener('click', () => {
  tl.reversed() ? tl.play() : tl.reverse()
})

 

See the Pen LYppreB by itsthomas (@itsthomas) on CodePen

Link to comment
Share on other sites

your code is fine, but if you want to simplify it even further with a little power tip you can toggle the reversed() state like so:

 

playBtn.addEventListener('click', () => {
  tl.reversed(!tl.reversed())
})

that basically says set the reversed() state to the opposite of the current reversed() state. 

 

  • Like 5
Link to comment
Share on other sites

  • 6 months later...
2 hours ago, ZachSaucier said:


playBtn.addEventListener('click', () => tl.play(), { once: true })

 

Thank you, but I'm unsure where to add this? 

And I'm not sure if I explained myself properly, but what I want is that each click (open and close button) completes before being clicked again. At the moment I can click and close quickly causing a flash

 

Here is my code pen -

See the Pen bGeQWbQ by NewbieRuby (@NewbieRuby) on CodePen

 

Thank you 

Link to comment
Share on other sites

11 minutes ago, ZachSaucier said:

@TrulyNewbie Thanks for the minimal demo. First off: use the new syntax. It's sleeker and lets you use new features. Upgrading is easy!

 

Here's how I might do that sort of thing, sticking to more performant properties:

 

 

Thank you for this. I really appreciate it.

I'm sorry to be a pain, but if you click the button repeatedly, it starts and stops (causing a flash). How can I make it so the transition completes before the being pressed again?

 

Thank you

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