JSFiddle - React, Tailwind, and code Playground

by Alex

HTML

<div class="container">
  <div class="el"></div>
</div>

CSS

body{
  width :100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container{
  width: 600px;
  height: 200px;
  background: green;
  display: flex;
  align-items: center;
}

.el{
  width: 100px;
  height: 100px;
  background: red;
}

JavaScript

const container = document.querySelector('.container');
const element = document.querySelector('.el');

const duration = 500;
let start = 0;

const lerp = (min, max, value) => (1 - value) * min + value * max;

const round = (value, precision = 0) => {
    const multiplier = Math.pow(10, precision);

    return Math.round(value * precision) / precision;
};

const easeInOutSine = (value) => -(Math.cos(Math.PI * value) - 1) / 2;

const update = () => {
    const delta = performance.now() - start;
    const progress = Math.min(1, delta / duration);
    const value = easeInOutSine(progress);

    element.style.setProperty(
        'transform',
        `translate(${round(lerp(-100, 0, value), 1)}%, ${round(lerp(0, 100, value), 1)}%)`
    );

    if (delta < duration) {
        requestAnimationFrame(update);
    }
};

const reset = () => {
    element.style.setProperty('transform', 'translate(-100%, 0)');
};

const init = () => {
    reset();

    container.addEventListener('click', () => {
        start = performance.now();
        requestAnimationFrame(update);
    });
};

window.addEventListener('DOMContentLoaded', init);