Jump to content
Search Community

Looping through an array of elements to create timeline... am i doing it right?

navug test
Moderator Tag

Go to solution Solved by OSUblake,

Recommended Posts

I'm trying to loop through an array of elements (it could be images or paragraphs) and create the same tween for each one of them. But i wanna do it the right way (the efficient, readable and clean way)

 

In this article (https://css-tricks.com/tips-for-writing-animation-code-efficiently/) the author does some loops examples in tip #7 but he doesn't add all the tweens in a single timeline…

 

So, i’m wondering if this is the way to do it?

function createTween(element) {
 return gsap.from(element,{
  //animations
 })
}

function createTimeline() {
 const images = document.querySelectorAll("img");
 const tl = gsap.timeline();

  [...images].forEach(element => {
    tl.add(createTween(element))
  })
  
 return tl;
}

createTimeline()

 

thanks in advance

Link to comment
Share on other sites

  • Solution

Welcome to the forums @navug

 

3 hours ago, navug said:

But i wanna do it the right way (the efficient, readable and clean way)

 

There is no right way. That's something you'll figure out over time as every situation is unique. What works well in one case may not work that well in another. ?

 

And your code looks fine. If you wanted, you could shorten it a bit with GSAP's toArray utility.

https://greensock.com/docs/v3/GSAP/UtilityMethods/toArray()

 

function createTimeline() {
 const tl = gsap.timeline();

  gsap.utils.toArray("img").forEach(element => {
    tl.add(createTween(element))
  });
  
 return tl;
}

 

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