Jump to content
Search Community

Gsap click toggle hide show, two different tweens on same element

Dustin 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

html

<button class="btn">Show / Hide</button>
<br><br>
<div class="box"></div>

css

.box {
    width: 100px;
    height: 100px;
    background-color: blue;
    opacity: 0;
}

javascript

const btn = document.querySelector('.btn');
const box = document.querySelector('.box');

const showBox = new TimelineMax({paused: true});
//alias for brevity 
const sb = showBox;

const hb = new TimelineMax({paused: true}); //hidebox

btn.addEventListener('click', function(){
	if(box.classList.contains('active') !== true) {
      sb.play();
    	sb.set(box, {opacity: 0, y: 0});
    	sb.fromTo(box, 0.5, {opacity: 0, y: 0}, {opacity: 1, y: 0});
        box.classList.add('active');
    }
    else if(box.classList.contains('active')) {
      hb.play();
    	hb.fromTo(box, 0.5, {opacity: 1, y: 0}, {opacity: 0, y: -100});
        box.classList.remove('active');
    }
});

 

New to the forum. I am looking to be able to show an element with one tweened animation and hide with a different animation by clicking the same button. In this case the show is a fade in and the hide is a fade out with a vertical translate. I tried by toggling the .active class and conditionally show or hide based on whether box has the class or not. I have only got it to work once (toggle on off for two clicks) and then it stops. Can someone tell me where i'm going wrong. I want to be able to keep this vanilla js, thanks.

 

demo

 

 

Link to comment
Share on other sites

Problem was your box was covering the buttons so subsequent clicks were not happening. You either change the z-index of the elements or change the order in html.

 

Also, you don't need to add your tweens in the timeline, it is going to add new tweens to your timelines on every single click. Using tweenmax or local timeline is enough in this scenario. I also tweaked your conditions as second if statement was unnecessary.

 

See the Pen ZRGVOb?editors=0010 by Sahil89 (@Sahil89) on CodePen

 

  • Like 8
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...