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

(Joyce) #1

Velocity object is used to invoke animations instead of specific jQuery element objects.


When you’re using Velocity without jQuery, you’re no longer animating jQuery
element objects, but rather raw Document Object Model (DOM) elements. Raw DOM
elements can be retrieved using the following functions:


document.getElementByID(): Retrieve an element by its ID attribute.
document.getElementsByTagName(): Retrieve all elements with a
particular tag name (e.g. a, div, p).
document.getElementsByClassName(): Retrieve all elements with a
particular CSS class.
document.querySelectorAll(): This function works nearly identically to
jQuery’s selector engine.
Let’s further explore document.querySelectorAll() since it will probably be
your weapon of choice when selecting elements without the aid of jQuery. (It’s a
performant function that’s widely supported across browsers.) As with jQuery’s element
selector syntax, you simply pass querySelectorAll a CSS selector (the same
selectors you use in your stylesheets for targeting elements), and it will return all matched
elements in the form of an array:


Click here to view code image
document.querySelectorAll(“body”); // Get the body element
document.querySelectorAll(“.squares”); // Get all elements with the “square”
class
document.querySelectorAll(“div”); // Get all divs
document.querySelectorAll(“#main”); // Get the element with an id of “main”
document.querySelectorAll(“#main div”); // Get all divs within “main”
If you assign the result of one of these lookups to a variable, you can then reuse that
variable to animate the targeted element(s):


Click here to view code image
// Get all div elements
var divs = document.querySelectorAll(“div”);
// Animate all the divs
Velocity(divs, { opacity: 0 }, 1000);
Since you’re no longer extending jQuery element objects, you may be wondering how
to chain animations back-to-back, like this:


Click here to view code image
// These chain onto one another
$element
.velocity({ opacity: 0.5 }, 1000)
.velocity({ opacity: 1 }, 1000);
To reenact this pattern without the aid of jQuery, simply call animations one after
another:


Click here to view code image
// Animations on the same element automatically chain onto one another.
Velocity(element, { opacity: 0 }, 1000);

Free download pdf