Dominicentek Gaming
Dominicentek Gaming

Reputation: 127

Moving a div up and then down

I have my code that supposes to animate div in a way that it moves up and then down. But it doesn't work and I don't know why.

document.getElementById('div').style = 'width: 50px; height: 50px; background-color: blue; left: 10px; bottom: 10px; position: absolute; animation-name: up; animation-duration: 2s;';
setTimeout(function() {
document.getElementById('div').style = 'width: 50px; height: 50px; background-color: blue; left: 10px; bottom: 10px; position: absolute; animation-name: down; animation-duration: 2s;'
}, 2 * 1000);
setTimeout(function() {
document.getElementById('div').style = 'width: 50px; height: 50px; background-color: blue; left: 10px; bottom: 10px; position: absolute;'
}, 2 * 1000);
@keyframes up {
from (bottom: 10);
to (bottom: 50);
}
@keyframes down {
from (bottom: 50);
to (bottom: 10);
}
<div id="div"></div>

Upvotes: 1

Views: 570

Answers (2)

fbfatboy
fbfatboy

Reputation: 401

css is enough!

@keyframes upAndDown {
  0% {
    bottom: 5px;
  }

  100% {
    bottom: 10px;
  }
}

.wrapper {
        position: relative;
        width: 100px;
        height: 100px;
        border: 1px solid black;
      }
      .content {
        position: absolute;
        bottom: 5px;
        width: 20px;
        height: 20px;
        background-color: red;
        animation: upAndDown 1s ease-in-out 2s infinite;
      }
<div class="wrapper">
      <div class="content"></div>
    </div>

Upvotes: 0

johannchopin
johannchopin

Reputation: 14844

With the translateY property you can move an html element up or down. Just use it in a css animation and you are fine:

@keyframes upToDown {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-30px);
  }
  100% {
    transform: translateY(0);
  }
}

Here you have the full example:

div {
  background: red;
  margin-top: 50px;
  animation: upToDown 2s infinite;
}

@keyframes upToDown {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-30px);
  }
  100% {
    transform: translateY(0);
  }
}
<div>
  a div
</div>

Upvotes: 2

Related Questions