📹 Video
-
Create a box with basic styles in index.html.
- div with id="box"
<div id="box"></div>
- Create css file and link it in the head of your html.
<link rel="stylesheet" href="./styles.css">
- Add basic styles.
#box { width: 25px; height: 25px; background-color: deepskyblue }
-
Now start your server.
yarn dev
- Switch to your index.js file to add an event.
- Add event listener.
document.addEventListener("click", event => {})
- Add TweenMax inside event listener.
document.addEventListener("click", event => { TweenMax.to("#box", 1, { x: 100, y: 100}) })
- TweenMax syntax is
TweenMax.to("selectedElement", duration(in seconds), {properties})
- TweenMax will move the "selectedElement" to the {properties} in the time set by duration.
- So the code from above will move our div with id box
"#box"
tox = 100px
andy = 100px
in1
second.
- Grab the location of your click.
- This can be done by accessing the clientX and clientY properties from the click event.
document.addEventListener("click", event => { const {clientX, clientY} = event })
- Use the locations inside your TweenMax.
document.addEventListener("click", event => { const {clientX, clientY} = event TweenMax.to("#box", 1, { x: clientX, y: clientY}) })
- Check it out . . . not quite right just yet is it?
- Eliminate body margin.
- Inside your CSS file,
body { margin: 0; }
- Check it out . . . now the corner lines up with the pointer click, but to make it center on the pointer keep going.
- Align the center of the box to the x and y coordinates.
- Use TweenMax.set, syntax looks like this
TweenMax.set("selectedElement", {properties})
- This will set the {properties} of the "selectedElement" from the get go and keep them throughout animation.
TweenMax.to("#box", {xPercent: -50, yPercent: -50})
- Check it out . . . nice Right!?