Jump to content
Search Community

Accordion Timeline Not Working on First Click

mulegoat test
Moderator Tag

Go to solution Solved by Cassie,

Recommended Posts

Hi everyone,

 

I've got an issue with an accordion that I cobbled together after viewing a thread on here. Zachs original pen used a basic tween to toggle open/close states

See the Pen gOWGKQZ by ZachSaucier (@ZachSaucier) on CodePen

 

I ammended mine slightly to use a timeline to tween the accordion content and animate the menu icon. Works fine however I have to click the accordion menu item twice before it works? After the first item is expanded everything works as it should but I can't figure out why that extra click is required at the start? Any help would be great. My accordion function:

 

function initAccordion() {

  const accordion = select('.js-accordion');

  if (!accordion) {
    return;
  }

  else{

    const groups = gsap.utils.toArray('.js-accordion__group');
    const menus = gsap.utils.toArray('.js-accordion__menu');
    const animations = [];

    groups.forEach(group => createAnimation(group));

    menus.forEach(menu => {
      menu.addEventListener('click', () => toggleAnimation(menu));
    });

    function toggleAnimation(menu) {
      // Save the current state of the clicked animation
      const selectedReversedState = menu.animation.reversed();
      
      // Reverse all animations
      animations.forEach(animation => animation.reverse());
      
      // Set the reversed state of the clicked accordion element to the opposite of what it was before
      menu.animation.reversed(!selectedReversedState);
    }

    function createAnimation(element) {
      const menu = element.querySelector('.js-accordion__menu');
      const box  = element.querySelector('.js-accordion__content');
      const icon  = element.querySelector('.js-accordion__icon');
      
      gsap.set(box, { height: 'auto'})
      gsap.set(icon, { rotation: 90})

      const tlAccordion = gsap.timeline({
        reverserd:true,
        paused: !0,
        onComplete: updateLoco
      });
      
      // Keep a reference to the animation on the menu item itself
      tlAccordion     
        .from(box, {
          height: 0, 
          duration: 0.5, 
          ease: 'power1.inOut'
        })
        .to(icon, {
          duration:0.25,
          rotation:-90,
          ease:'linear'
        }, '<');
      
      menu.animation = tlAccordion;
      animations.push(tlAccordion);
    }

  }

}

 

Many thanks in advance

 

Marco

See the Pen bGryvWe by mulegoat (@mulegoat) 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.
×
×
  • Create New...