Web Animation using JavaScript: Develop & Design (Develop and Design)

(やまだぃちぅ) #1

Using Velocity: Basics


To get oriented to Velocity, we’ll start with the basic components: arguments, properties,
values, and chaining. Since jQuery is so ubiquitous, it is also important to look at the
relationship between Velocity and jQuery.


Velocity and jQuery


Velocity functions independently of jQuery, but the two can be used in combination. It’s
often preferable to do so to benefit from jQuery’s chaining capabilities: When you’ve
preselected an element using jQuery, you can extend it with a call to .velocity() to
animate it:


Click here to view code image
// Assign a variable to a jQuery element object
var $div = $(“div”);
// Animate the element using Velocity
$div.velocity({ opacity: 0 });
This syntax is identical to jQuery’s own animate function:
$div.animate({ opacity: 0 });
All the examples in this book use Velocity in combination with jQuery, and therefore
follow this syntax.


Arguments


Velocity accepts multiple arguments. Its first argument is an object that maps CSS
properties to their desired final values. The properties and their accepted value types
correspond directly to those used in CSS (if you’re unfamiliar with basic CSS properties,
pick up an introductory HTML and CSS book before reading this one):


Click here to view code image
// Animate an element to a width of “500px” and to an opacity of 1.
$element.velocity({ width: “500px”, opacity: 1 });


    Tip

In  JavaScript, if  you’re  providing   a   property    value   that    contains    letters
(instead of only integers), put the value in quotes.

You can pass    in  an  object  specifying  animation   options as  a   second  argument:

Click here to view code image
$element.velocity({ width: “500px”, opacity: 1 }, { duration: 400, easing:
“swing” });
There’s also a shorthand argument syntax: Instead of passing in an options object as a
second argument, you can use comma-separated argument syntax. This entails listing
values for duration (which accepts an integer value), easing (a string value), and complete
(a function value) in any comma-separated order. (You’ll learn what all of these options do
momentarily.)

Free download pdf