JSFiddle - React, Tailwind, and code Playground
by podgorniy
HTML
<div id="animated"></div>
CSS
#animated {
width: 20px;
height: 20px;
border-radius: 10px;
background: purple;
box-shadow: 0 0 11px #000;
position: absolute;
top: 10px;
}
JavaScript
function now () {
return (new Date()).getTime()
}
function swing (p) {
return (- Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
function animate (callback, animationTime) {
var animationStartTime;
animationStartTime = now();
(function animationTic () {
var animationFrameTime;
var animationTimeDelta;
var progress;
animationFrameTime = now();
animationTimeDelta = animationFrameTime - animationStartTime;
if (animationTimeDelta >= animationTime) {
progress = 1;
} else {
progress = animationTimeDelta / animationTime;
setTimeout(animationTic, (1000/60));
}
callback(progress);
}());
}
function doAnimation () {
var startValue;
var endValue;
var animatedNode;
startValue = 0;
endValue = 200;
animatedNode = document.getElementById('animated');
animate(function (progress) {
console.log(progress);
progress = swing(progress);
console.log(progress);
console.log('--')
animatedNode.style.left = (startValue + (progress * endValue)) + 'px';
}, 2000)
}
document.onclick = function () {
doAnimation();
}