JSFiddle - React, Tailwind, and code Playground
HTML
<div id="parent">
<div id="child">
</div>
</div>
CSS
#parent {
height: 200px;
width: 200px;
background-color: lightblue;
}
#child {
height: 100px;
width: 100px;
background-color: lightgreen;
}
JavaScript
const animate = (element, duration, distance) => {
let start;
const durationMs = duration * 1000;
const speed = distance / durationMs;
const step = (timestamp) => {
if (start === undefined)
start = timestamp;
const elapsed = timestamp - start; // milliseconds
element.style.transform = 'translateX(' + Math.min(speed * elapsed, distance) + 'px)';
if (elapsed < durationMs) { // Stop the animation after duration
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
}
animate(document.getElementById('child'), 1, 100);