Control an Array of Elements with the Same Animation in GreenSock

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

Any GreenSock animation can accept an array of dom elements. This lesson shows you how to easily create and tween 100 divs to the same point.

Instructor: [00:00] I'm going to use a neat trick to create an array of 100 divs by saying arrayFrom and just an object with a length of 100, and then a function that will return document.createElement with a string of div. Now we have a divs array loaded with 100 created divs. I'm going to loop through these, divs.forEach, and grab each div. I'll use TweenMax to set some properties on each div.

[00:34] Take the div and set the following properties. Position to absolute, the x value to a string of math.random * window.innerWidth pixels. I'll copy this down and y can be math.random * window.innerHeight pixels.

[01:02] We'll have each width be 20, each height be 20, a background-color of green, and we'll set a border to 3 pixels solid black. Then for each of those after they're set, we can just document.bodyAppendChild(div).

[01:26] With all that done, I'll hit save and you can see a whole bunch of divs show up scattered on the screen. With all these divs, it's actually possible to tween them all at the same time. I'm just going to document.addEventListener("click") and grab the event.

[01:42] We'll grab the x and y off of the event, and say TweenMax.to, pass in the array of divs, have it take 1 second, and we'll tween to that x and y.

[01:56] Refreshing will rescatter. Then I'll click and you can see they all tween to where I clicked. If I click again, you'll see they'll all come together with no scattering. I'll show that again, randomize, and click, and you'll see them all come together at that point.

egghead
egghead
~ 28 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today