How to pick random element of a certain class | GreenSock - GSAP

350 Views Asked by At

I would like to animate only certain elements of a certain class from an SVG image with GreenSock (GSAP).

To animate all the elements of a class, I would do:

gsap.to(".class", {duration: 5, rotate: 180, transformOrigin: 'center center', repeat: -1});

Now, how can I pick one (or more) random element(s) of and animate them like so.

What I want to do is animate them randomly by turn and indefinitely.

1

There are 1 best solutions below

0
On BEST ANSWER

If you really need to create individual tweens, you would have to have a list (array) of all of your elements, keep track of which ones you've started to animate already, and sequentially fire off new tweens for them. Something like this:

// Get your elements in array form
const elems = gsap.utils.toArray(".class");

// Shuffle the array
const shuffled = (elems) => elems.sort(() => Math.random() - 0.5);

// Then fire of a new tween for each one, removing it from the array
while (shuffled.length > 0) {
  let elem = shuffled.pop();
  gsap.to(elem, {...}); // optionally keep track of the count to offset it or whatever
}

However, GSAP can do this sort of thing for you using staggers! How you do so depends on your needs. Since you haven't made those clear, here's a general idea of how to so this sort of thing:

gsap.to(".class", {
  duration: 5, 
  rotate: 180, 
  transformOrigin: 'center center', 
  stagger: { 
    each: 0.1, // or even a negative value if you want them to all be started initially
    repeat: -1 
  }
});

By the way, you're more likely to get an even faster response and additional opinions on your requests like this by posting in GreenSock's official forums.