Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Control an Array of Elements with the Same Animation in GreenSock

    John LindquistJohn Lindquist
    greensockGreenSock

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

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

    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.

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

    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.

    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.

    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.