Jump to content
Search Community

forEach Animation Approach

Mike790 test
Moderator Tag

Recommended Posts

Hi everyone!  

 

I want to make sure that I'm taking the right approach to animating a forEach function.  Between the two scripts below, which would be the better approach?  They both appear to be equal in performance, so I'm not sure if it's just a matter of preference at this point or if one approach outweighs the other.

 

Thanks in advance for any guidance on my question!

 

 

function sectionFadeAnimations(btn, selectedSection) {
 
  gsap.to(onPageSections, {
    opacity: 0,
    duration: 0.2,
    display: 'none',
    onComplete: () => {
      document.querySelectorAll(selectedSection).forEach(section => {
        section.style.display = 'block';
        gsap.to(section, { opacity: 1duration: 0.2 });
      });
    }
  });
 
}
 
document.querySelectorAll('.on-page-menu button').forEach(btn => {
 
  btn.addEventListener('click', () => {
 
      let selectedSection = btn.classList[0];
 
      sectionFadeAnimations(btn, selectedSection);    
 
  });
 
});


 
---------------------------------------------------------------------------------------------------
 
gsap.utils.toArray('.on-page-menu button').forEach(btn => {
 
  btn.addEventListener('click', () => {
 
      let selectedSection = btn.classList[0];
 
      gsap.to(onPageSections, {
        opacity: 0,
        duration: 0.2,
        display: 'none',
        onComplete: () => {
          document.querySelectorAll(selectedSection).forEach(section => {
            section.style.display = 'block';
            gsap.to(section, { opacity: 1duration: 0.2 });
          });
        }
      });
 
  });
 
});
Link to comment
Share on other sites

Hey Mike. They're pretty equivalent, mostly just programming style being different. 

 

A couple of comments (not about the difference between the two) though:

  • Are you really wanting to select all of the "selectedSection"s and change their opacity? There's likely a better way to write that section but given the lack of context it's pretty hard to make a recommendation. If you made a minimal demo of your situation that'd be really helpful: 
  • gsap.set() is a good way to avoid having to do elem.style.property (especially useful if you are setting a lot of properties at the same time).
Link to comment
Share on other sites

  • 1 year later...

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