Animation with RAF

Creating a javascript animation with the RequestAnimationFrame API

by Michael Barros

HTML

<div class="container">
  <div id="animateMe" class="content">
  </div>
</div>

<button id="start" class="start">Animate me!</button>

<p>
<div>
  <input type="text" name="lname">
</div>

CSS

.container {
  width: 500px;
  height: 100px;
  border: 3px solid #8cc73f;
  position: relative;
  border-radius: 40px 0;
}

.content {
  width: 30px;
  height: 30px;
  top: 35px;
  background-color: #8cc73f;
  border-radius: 40px;
  position: absolute;
  left: 0;
}

.start {
  line-height: 30px;
  margin-top: 10px;
  color: #fff;
  background-color: #567d23;
  font-size: 14px;
  border-radius: 40px;
  border: none;
}

JavaScript

var start = null;
var element = document.querySelector('#animateMe');
var max = 470;

function moveLeft(timestamp) {
  if (!start) start = timestamp;
  var progress = timestamp - start;
  var newPosition = Math.min(progress / 10, max);
  element.style.left = newPosition + 'px';
  if (newPosition < max) {
    window.requestAnimationFrame(moveLeft);
  }
}

document.querySelector('#start').addEventListener('click', function() {
  window.requestAnimationFrame(moveLeft);
});