JSFiddle - React, Tailwind, and code Playground

by Chris Ball

HTML

<div class="mydiv"></div>

<button class="btn">twat</button>

CSS

body {
	position: relative;
}

.mydiv {
	background: red;
	display: block;
	height: 50px;
	position: absolute;
	width: 50px;
	z-index: -1;
}

JavaScript

var adiv = document.querySelector('.mydiv')

function move(el, distance, duration) {
	requestAnimationFrame((timestamp) => {
		starttime = timestamp
		moveLoop(timestamp, el, distance, duration) // 400px over 1 second
	})
}

function moveLoop(timestamp, el, dist, duration){
    var runtime = timestamp - starttime
    var progress = runtime / duration
    progress = Math.min(progress, 1)
    el.style.left = (dist * progress).toFixed(2) + 'px'
    if (runtime < duration){ // if duration not met yet
        requestAnimationFrame(function(timestamp){ // call requestAnimationFrame again with parameters
            moveLoop(timestamp, el, dist, duration)
        })
    }
}

var btn = document.querySelector('.btn')

btn.addEventListener('click', ()=>{
	move(adiv, 400, 2000)
})