Developers often use animations to make their web pages elegant and user-friendly. In JavaScript, programmers use the window.requestAnimationFrame()
method of the window
object to create animations.
This method generates animations that are in sync with the processing speed. It also slows down the animation's loading time when it is not in use, and saves the browser's resources while rendering web pages.
Let's take a look at this method's syntax
window.requestAnimationFrame(callback);
This method has a single parameter:
callback
: This function creates the next frame of the animation. It takes a timestamp
as an argument to make changes in the animation variables when they are rendered on the screen.The return value of this method is a non-zero long integer, which is a unique identifier for the animation in the callback
function.
The code below demonstrates the use of the window.requestAnimationFrame()
method:
<div>
tag that encapsulates the <img>
and the <h4>
tags that we want to animate.<script>
tags that enclose actual JavaScript code that depict the use of window.requestAnimationFrame()
. We can further break them down as follows:start
to null
. We fetch the <div>
tag by using document.getElementById()
to apply the animation.startAnimation()
. This method checks if the start
variable is null
using an if-statement
. It then adds linear motion to the div
tag using the style.transform
property.translateX
property of CSS and the Math.min()
function to apply the animation accordingly.window.requestAnimationFrame()
method then passes the callback function startAnimation()
, which renders the next frame.startAnimation()
method and renders the animation as seen in the output tab above.Note: To learn more about the
Math.min()
function, we can refer to this link.