Skip to content

Advanced Value Functions

Ryc O'Chet edited this page Jun 3, 2018 · 2 revisions
- NOTE: This documentation is for Velocity v2.

Advanced: Value Functions

Property values can be passed functions. These functions are called once per element - immediately before the element begins animating. Therefore, when looping/reversing, the functions are not repeatedly re-called.

The value returned by the function is used as the property value:

element.velocity({
    opacity: function() {
        return Math.random();
    }
});

Value functions are passed the iterating element as their context, plus a first argument containing the element's index within the set, a second argument containing the total length of the set, a third argument containing an array of all the elements, and a fourth argument containing the name of the property it is used on. By using these values, visual offseting can be achieved:

element.velocity({
    top: function(i, total, elements, propertyName) {
        // Generate the top value.
        return i * 10;
    }
});

In addition to helping contain animation logic within Velocity, value functions are the most performant way of differentiating properties amongst a set of elements - as opposed to pre-iterating through them and calling Velocity once for each, which forgoes some of Velocity's optimisations.