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

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.