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

(やまだぃちぅ) #1

Technique: Avoid affecting neighboring elements


It’s important to consider the impact of an element’s animation on neighboring elements.


Problem


When an element’s dimensions are animated, the changes often affect the positioning of
nearby elements. For example, if an element between two sibling elements shrinks in
width, the siblings’ absolute positions will dynamically change so they remain next to the
animating element. Another example might be animating a child element nested inside a
parent element that doesn’t have explicitly defined width and height properties.
Accordingly, when the child is being animated, the parent will also resize itself so that it
continues to fully wrap itself around the child. In effect, the child element is no longer the
only element being animated—the parent’s dimensions are also being animated, and that’s
even more work for the browser to perform upon each tick in an animation loop!


There are many CSS properties whose modification can result in dimensional and
positional adjustments to neighboring elements, including top, right, bottom, and
left; all margin and padding properties; border thickness; and the width and
height dimensions.


As a performance-minded developer, you need to appreciate the impact that animating
these properties can have on your page. Always ask yourself how each property you’re
attempting to animate affects nearby elements. If there’s a way to rewrite your code such
that you can isolate elements’ changes from one another, then consider doing so. In fact,
there is an easy way to do just this—on to the solution!


Solution


The simple solution to avoid affecting neighboring elements is to animate the CSS
transform properties (translateX, translateY, scaleX, scaleY, rotateZ,
rotateX, and rotateY) whenever possible. The transform properties are unique in that
they elevate targeted elements to isolated layers that are rendered separately from the rest
of the page (with a performance boost courtesy of your GPU), so that neighboring
elements aren’t affected. For example, when animating an element’s translateX to a
value of “500px", the element will move 500px rightward while superimposing itself on
top of whatever elements exist along its animation path. If there are no elements along its
path (that is, if there are no nearby elements for it to affect), then using translateX will
have the same net effect on the look of your page as if you had animated using the much
slower left property.


Hence,  whenever    possible,   an  animation   that    once    looked  like    this:

Click here to view code image
// Move the element 500px from the left
$element.velocity({ left: “500px” });
should be refactored into this:


Click here to view code image
// Faster: Use translateX

Free download pdf