JSFiddle - React, Tailwind, and code Playground
by Sunny Sharma
HTML
<div id='butn'></div>
<div id='box' onclick='fun();' ></div>
CSS
#butn{
position:absolute;
width:20px;
height:20px;
background-color:#333;
}
#box{
position:absolute;
width:50px;
height:50px;
top:30px;
background-color:#06f;
}
JavaScript
var doAnimation=true;
var timer=0;
var start=undefined;
function animate(elem,style,from,to,time)
{
if(!elem && doAnimation) return;
if(start==undefined)start = new Date().getTime();
timer = setInterval(function(){
var step = Math.min(1,(new Date().getTime()-start)/time);
elem.style[style] = (from+step*(to-from))+'px';
if( step == 1){
doAnimation=false;
clearInterval(timer);
elem.style[style] = from+'px';
start=undefined;
}},25);
}
function fun(){
doAnimation=!doAnimation;
if(doAnimation){play();}
else{pause();}
}
function play(){
animate( document.getElementById('box'),'left',0 , 200, 7000);
}
function pause(){
clearInterval(timer);
}
$(document).ready(function(){
play();
});