JSFiddle - React, Tailwind, and code Playground

by MsCom Technology

HTML

<div id='mover'></div>
<div id='trigger'></div>

CSS

#mover {
    position: absolute;
    left: 150px;
    width: 100px;
    height: 60px;
    background: red;
}

#trigger {
    width: 25px;
    height: 25px;
    background:green;
}

JavaScript

var _requestAnimationFrame = function(win, t) {
  return win["webkitR" + t] || win["r" + t] || win["mozR" + t]
          || win["msR" + t] || function(fn) { setTimeout(fn, 60) }
}(window, "equestAnimationFrame");

var goingLeft = false;

function animate(item) {
 
  var duration = 1000*item.time,
      end = +new Date() + duration;
 
  var step = function() {
 
    var current = +new Date(),
        remaining = end - current;
 
    if(remaining < 60) {
      item.run(1);  //1 = progress is at 100%
      return;
 
    } else {
      var rate = 1 - remaining/duration;
      item.run(rate);
    }
 
    _requestAnimationFrame(step);
  }
  step();
}

function goLeft() { 
    animate({
        time: 0.5,
        run: function(rate) {
            document.getElementById('mover').style.left = rate * (300 - 150) + 150 + 'px';
        }
    });
}

function goRight() { 
    animate({
        time: 0.5,
        run: function(rate) {
            document.getElementById('mover').style.left = 300 - (rate * 150) + 'px';
        }
    });
}

function move() {
    if (goingLeft) {
         goRight();
    } else {
         goLeft();   
    }
    goingLeft = !goingLeft;
}

document.getElementById('trigger').addEventListener('click', move);