animate dom with dynamic animation time in typescript

To animate a DOM element with dynamic animation time using TypeScript, one can use the requestAnimationFrame method.

Here's an example of a function that animates a div element with a dynamic duration:

index.ts
function animateDivWithDuration(element: HTMLElement, duration: number) {
  let start: number;

  function animate(time: number) {
    if (!start) start = time;
    const elapsed = time - start;

    const progress = Math.min(elapsed / duration, 1); // Calculate the animation progress
    element.style.transform = `translateX(${progress * 100}%)`;

    if (progress < 1) {
      // If the animation is not finished, request another animation frame
      window.requestAnimationFrame(animate);
    }
  }

  // Start the animation
  window.requestAnimationFrame(animate);
}
574 chars
20 lines

The animate function is called recursively using requestAnimationFrame. It calculates the progress of the animation based on the duration parameter and updates the CSS transform property of the element accordingly.

To use this function, simply pass in the target element and the duration:

index.ts
const divElement = document.querySelector('#myDivElement')!;
const duration = 1000; // 1 second

animateDivWithDuration(divElement, duration);
143 chars
5 lines

This will animate the divElement horizontally over a period of 1 second.

gistlibby LogSnag