📹 Video
- Use the 🤔Array.from() method to create an array with 100 div elements.
const divs = Array.from({length: 100}, () =>
document.createElement("div")
)
- 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"
})
})
- 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.
- Add and event listener for a click event, you will need the event param.
document.addEventListener("click", event => {})
- Use the x and y properties from the click.
const { x, y } = event
- 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 })
})