user11586294
user11586294

Reputation:

Animating a div element

Looking to make a specific animation for a div element. I want it to go down (smoothly) and when it reaches the bottom of the screen to come back up (smoothly).

The code I have is as follows:

The Javascript part at the If statement is where I am having difficulties. I want the box to come down and come back up smoothly.

HTML:

<div class="verticalDiv" id="verticalDiv" onclick="verticalMove()"></div>

CSS:

.verticalDiv {
  position: absolute;
  top: 0px;
  right: 500px;
  width: 100px;
  height: 100px;
  margin: 100px auto;
  background: red;
}

JS:

myVar1 = setInterval(verticalMove, 50);
v = 0;
function verticalMove() {
    redBox = document.getElementById('verticalDiv')

    redBox.style.top = v + "px";
        if (v >= 0) {
            v++;} 

        if (v === 200) {
            v--;
        }
    console.log(v);
}

Upvotes: 2

Views: 190

Answers (2)

m51
m51

Reputation: 2010

I think, best way is to use css animation. You don't have to care about animation logic. Just use keyframes. Here is example:

HTML

<div id="verticalDiv" class="verticalDiv"></div>

CSS

.verticalDiv {
    height: 20px;
    width: 20px;
    background: red;
}

@keyframes move {
    0% { transform: translateY(0); }
    50% { transform: translateY(200px); }
    100% { transform: translateY(0); }
}

.verticalDiv.move {
    animation: move 3s ease-in-out;
}

JS

const verticalDiv = document.getElementById('verticalDiv');
verticalDiv.addEventListener('click', () => {
    verticalDiv.classList.toggle('move');
});

WORKING DEMO click on red div to start animation.

BTW If you want animate something. It is always better to animate properties that doesn't force layout updates: transform and opacity. Other properties, like top, bottom, margin are expensive for browser to animate. You should avoid them if possible. Read more

Upvotes: 3

tevemadar
tevemadar

Reputation: 13205

You need to differentiate between the two phases, moving down and moving up. It can be a simple true/false boolean, but storing a "speed" or "delta" value (like +/-1) is also a very typical approach.

var v = 0;
var delta=1;
function verticalMove() {
    redBox = document.getElementById('verticalDiv')
    v += delta;
    redBox.style.top = v + "px";
    if (v <= 0) delta = 1;
    if (v >= 50) delta = -1;
}
function startMove(event) {
    setInterval(verticalMove,30);
    event.target.onclick="";
}
.verticalDiv {
  position: absolute;
  top: 0px;
  right: 500px;
  width: 100px;
  height: 100px;
  background: red;
}
<div class="verticalDiv" id="verticalDiv" onclick="startMove(event)"></div>

Upvotes: 2

Related Questions