Skip to content

Latest commit

 

History

History
79 lines (69 loc) · 2.7 KB

08-control-an-array-of-elements-with-the-same-animation-in-greensock.md

File metadata and controls

79 lines (69 loc) · 2.7 KB

Control and Array of Elements with the Same Animations in Greensock

📹 Video

Create 100 boxes and place them randomly

  1. Use the 🤔Array.from() method to create an array with 100 div elements.
const divs = Array.from({length: 100}, () => 
    document.createElement("div")
)
  1. Loop through the array with a 🤔.forEach() method and set the properties with TweenMax.set().
divs.forEach(div => {
    TweenMax.set(div, {
        position: "absolute",
        x: `${Math.random() * window.innerWidth}px`,
        y: `${Math.random() * window.innerHeight}px`,
        width: 20,
        height: 20,
        backgroundColor: "green",
        border: "3px solid black"
    })
})
  1. Mount each div in the .forEach() to the document's body.
document.body.appendChild(div)

All together

const divs = Array.from({length: 100}, () => 
    document.createElement('div')
)

divs.forEach(div => {
    TweenMax.set(div, {
        position: "absolute",
        x: `${Math.random() * window.innerWidth}px`,
        y: `${Math.random() * window.innerHeight}px`,
        width: 20,
        height: 20,
        backgroundColor: "green",
        border: "3px solid black"
    })
    
    document.body.appendChild(div)
})
  • Check it out . . . If you refresh the page the boxes will be randomly placed again due to the 🤔Math.random() used to set the x and y properties.

Collect the divs together with a click

  1. Add and event listener for a click event, you will need the event param.
    document.addEventListener("click", event => {})
  2. Use the x and y properties from the click.
    const { x, y } = event
  3. Use 🤔TweenMax.to() to animate them to the location of your click.
    TweenMax.to(divs, 1, { x, y })
    • Notice the selected Element is the entire array (divs).

All together

document.addEventListener("click", event => {
    const { x, y } = event

    TweenMax.to(divs, 1, { x, y })
})

📹 Go to Previous Lesson 📹 Go to Next Lesson