Skip to content

Instantly share code, notes, and snippets.

@ehpc
Created October 12, 2021 07:45
Show Gist options
  • Save ehpc/6ea2021857605af3baf5c13a825a4c17 to your computer and use it in GitHub Desktop.
Save ehpc/6ea2021857605af3baf5c13a825a4c17 to your computer and use it in GitHub Desktop.
JS animate movement with requestAnimationFrame and transition
function move(el, distance, duration) {
let startTime;
function recur() {
window.requestAnimationFrame((time) => {
if (startTime === undefined) {
startTime = time;
}
const elapsed = time - startTime;
const fraction = elapsed / duration;
const dx = Math.min(distance, distance * fraction);
console.log(time, elapsed, fraction, dx);
el.style.transform = `translateX(${dx}px)`;
if (elapsed < duration) {
recur();
}
});
}
recur();
}
function move2(el, distance, duration) {
el.style.transform = `translateX(${distance}px)`;
el.style.transition = `${duration}ms linear`;
}
move(document.querySelector(".movable"), 500, 3000);
move2(document.querySelector(".movable2"), 500, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment