The anime()
function provided by anime.js takes several
The values we provide for properties and property parameters don't have to be strings or numbers. They can also be functions.
Function-based values and parameters are used for customizing the animation based on the
The given code describes the syntax for creating a function-based value or property parameter.
anime({...//function-based valueproperty: function(target, index, targetsLength){return ...;},//function-based parameterproperty parameter: function(target, index, targetsLength){return ...;},});
Whether for a property or a property parameter, the function is called separately for each targeted element. The function takes three arguments:
target
: The currently targeted element
index
: Index of the currently targeted element
targetsLength
: Total number of targeted elements
The function's return value is assigned to that specific target's property/property parameter. See the examples below for elaboration.
For properties, such as translations or rotations, we can functionally set the value for each element. In the following example, we set the translateX
property of each element based on its index.
In the HTML section, we create 5 div
elements and style them to look like boxes using the box
class.
In the JavaScript section of the code, we use the anime()
function to animate each box.
Lines 1–2: We create an animation and target all elements with the box
class.
Lines 3–6: Instead of giving a single value for translateX
, we provide a function that takes the three parameters.
Line 4: We set the element's display value to its index using the innerHTML
attribute. This demonstrates that the target
parameter is just a normal DOM node.
Line 5: We return a value for translateX
that is calculated based on the index
. The element with index
0 will have translateX
set to 100, index
1 to 200, and so on.
Lines 7–8: We set the duration
and delay
to 1000 milliseconds each.
Note: Click here to learn about the
innerHTML
attribute.
As we can see, each box has a different value for translateX
. These values were set using a function-based value within a single call to the anime()
function. Function-based values save us from calling the anime()
function separately for each box.
Just as we provided a function for a property, we can also pass a function for a property parameter. In the following example, we set the delay
of each element based on its index.
For simplicity, we replicate the previous example but set the translateX
property to be 500 for all elements.
Lines 5–8: We give a function instead of providing a single value for delay
. The function returns a value for each targeted element based on its index
. In this case, index
0 will have delay
set to 500, index
1 to 1000, and so on.