quinta-feira, 4 de setembro de 2014

Animating Without jQuery

Animating Without jQuery


  • By Julian Shapiro

  • September 4th, 2014

  • JavaScriptjQueryTechniques

  • 2 Comments

There’s a fake faith in a web growth village that CSS animation is a usually performant approach to spur on a web. This parable has coerced many developers to desert JavaScript-based animation altogether, thereby (1) forcing themselves to conduct formidable UI communication within character sheets, (2) locking themselves out of ancillary Internet Explorer 8 and 9, and (3) forgoing a pleasing suit pattern production that are probable usually with JavaScript.


Reality check: JavaScript-based animation is mostly as quick as CSS-based animation — infrequently even faster. CSS animation usually appears to have a leg adult since it’s typically compared to jQuery’s $.animate(), that is, in fact, really slow. However, JavaScript animation libraries that bypass jQuery broach implausible opening by avoiding DOM strategy as many as possible. These libraries can be adult to 20 times faster than jQuery.


So, let’s pound some myths, dive into some real-world animation examples and urge a pattern skills in a process. If we adore conceptualizing unsentimental UI animations for your projects, this essay is for you.


Why JavaScript?


CSS animations are available when we need to shower skill transitions into your character sheets. Plus, they broach illusory opening out of a box — though your carrying to supplement libraries to a page. However, when we use CSS transitions to energy abounding suit pattern (the kind we see in a latest versions of iOS and Android), they turn too formidable to conduct or their facilities simply tumble short.


Ultimately, CSS animations extent we to what a selection provides. In JavaScript, by a really inlet of any programming language, we have an gigantic volume of judicious control. JavaScript animation engines precedence this fact to yield novel facilities that let we lift off some really useful tricks:


  • cross-browser SVG support1,

  • physics-based loader animations2,

  • timeline control3,

  • Bezier translations4.

Note: If you’re meddlesome in training some-more about performance, we can review Julian Shapiro’s “CSS vs. JS Animation: Which Is Faster?5” and Jack Doyle’s “Myth Busting: CSS Animations vs. JavaScript6.” For opening demos, impute to a opening pane7 in Velocity’s support and GSAP’s “Library Speed Comparison8” demo.


Velocity and GSAP


The dual many renouned JavaScript animation libraries are Velocity.js9 and GSAP10. They both work with and without11 jQuery. When these libraries are used alongside jQuery, there is no opening plunge since they totally bypass jQuery’s animation stack.


If jQuery is benefaction on your page, we can use Velocity and GSAP usually like we would jQuery’s $.animate(). For example, $element.animate( opacity: 0.5 ); simply becomes $element.velocity( opacity: 0.5 ).


These dual libraries also work when jQuery is not benefaction on a page. This means that instead of chaining an animation call onto a jQuery component intent — as usually shown — we would pass a aim element(s) to a animation call:


/* Working though jQuery */

Velocity(element, opacity: 0.5 , 1000); // Velocity

TweenMax.to(element, 1, opacity: 0.5 ); // GSAP

As shown, Velocity retains a same syntax as jQuery’s $.animate(), even when it’s used though jQuery; usually change all arguments rightward by one position to make room for flitting in a targeted elements in a initial position.


GSAP, in contrast, uses an object-oriented API design, as good as available immobile methods. So, we can get full control over animations.


In both cases, you’re no longer animating a jQuery component object, though rather a tender DOM node. As a reminder, we entrance tender DOM nodes by regulating document.getElementByID, document.getElementsByTagName, document.getElementsByClassName or document.querySelectorAll (which works likewise to jQuery’s selector engine). We’ll quickly work with these functions in a subsequent section.


Working Without jQuery


(Note: If we need a simple authority on operative with jQuery’s $.animate(), impute to a initial few panes in Velocity’s documentation.12)


Let’s try querySelectorAll serve since it will expected be your arms of choice when selecting elements though jQuery:


document.querySelectorAll("body"); // Get a physique element
document.querySelectorAll(".squares"); // Get all elements with a "square" class
document.querySelectorAll("div"); // Get all divs
document.querySelectorAll("#main"); // Get a component with an id of "main"
document.querySelectorAll("#main div"); // Get a divs contained by "main"

As shown, we simply pass querySelectorAll a CSS selector (the same selectors we would use in your character sheets), and it will lapse all matched elements in an array. Hence, we can do this:


/* Get all div elements. */
var divs = document.querySelectorAll("div");

/* Animate all divs during once. */
Velocity(divs, opacity: 0.5 , 1000); // Velocity
TweenMax.to(divs, 1, opacity: 0.5 ); // GSAP

Because we’re no longer attaching animations to jQuery component objects, we might be wondering how we can process animations behind to back, like this:


$element // jQuery component object
.velocity( opacity: 0.5 , 1000)
.velocity( opacity: 1 , 1000);

In Velocity, we simply call animations one after another:


/* These animations automatically process onto one another. */
Velocity(element, opacity: 0.5 , 1000);
Velocity(element, opacity: 1 , 1000);

Animating this approach has no opening obstacle (as prolonged as we cache a component being charcterised to a variable, instead of regularly doing querySelectorAll lookups for a same element).


(Tip: With Velocity’s UI pack, we can emanate your possess multi-call animations and give them tradition names that we can after anxiety as Velocity’s initial argument. See Velocity’s UI Pack documentation13 for some-more information.)


This one-Velocity-call-at-a-time routine has a outrageous benefit: If you’re regulating promises14 with your Velocity animations, afterwards any Velocity call will lapse an actionable guarantee object. You can learn some-more about operative with promises in Jake Archibald’s article15. They’re impossibly powerful.


In a box of GSAP, a fluent object-oriented API allows we to place your animations in a timeline, giving we control over scheduling and synchronization. You’re not singular to one-after-the-other cumulative animations; we can nest timelines, make animations overlap, etc:


var tl = new TimelineMax();
/* GSAP tweens process by default, though we can mention accurate insertion points in a timeline, including relations offsets. */
tl
.to(element, 1, opacity: 0.5 )
.to(element, 1, opacity: 1 );

JavaScript Awesomeness: Workflow


Animation is inherently an initial routine in that we need to play with timing and easings to get accurately a feel that your app needs. Of course, even once we consider a pattern is perfect, a customer will mostly ask non-trivial changes. In these situations, a docile workflow becomes critical.


While CSS transitions are impressively easy to shower into a plan for effects such as hovers, they turn bulky when we try to process even tolerably formidable animations. That’s because CSS provides keyframe animations, that concede we to organisation animation proof into sections.


However, a core scarcity of a keyframes API is that we contingency conclude sections in percentages, that is unintuitive. For example:


@keyframes myAnimation 
0%
opacity: 0;
transform: scale(0, 0);

25%
opacity: 1;
transform: scale(1, 1);

50%
transform: translate(100px, 0);

100%
transform: translate(100px, 100px);



#box
animation: myAnimation 2.75s;


What happens if a customer asks we to make a translateX animation 1 second longer? Yikes. That requires redoing a math and changing all (or most) of a percentages.


Velocity has a UI pack16 to understanding with multi-animation complexity, and GSAP offers nestable timelines17. These facilities concede for wholly new workflow possibilities.


But let’s stop priesthood about workflow and indeed dive into fun animation examples.


JavaScript Awesomeness: Physics


Many absolute effects are practicable exclusively around JavaScript. Let’s inspect a few, starting with physics-based animation.


The application of production in suit pattern hits on a core component of what creates for a good UX: interfaces that upsurge naturally from a user’s submit — in other words, interfaces that belong to how suit works in a genuine world.


GSAP offers production plugins that adjust to a constraints of your UI. For example, a ThrowPropsPlugin marks a energetic quickness of a user’s finger or mouse, and when a user releases, ThrowPropsPlugin matches that analogous quickness to naturally slip a component to a stop. The ensuing animation is a customary tween that can be time-manipulated (paused, reversed, etc.):


See a Pen Draggable (Mini)18 by GreenSock (@GreenSock3319) on CodePen3431262320.


Velocity offers an easing form formed on open physics. Typically with easing options, we pass in a named easing type; for example, ease, ease-in-out or easeInOutSine. With open physics, we pass a two-item array consisting of tragedy and attrition values (in brackets below):


Velocity(element, left: 500 , [ 500, 20 ]); // 500 tension, 20 friction

A aloft tragedy (a default of 500) increases a sum speed and bounciness. A reduce attrition (a default of 20) increases finale quivering speed. By tweaking these values, we can alone fine-tune your animations to have opposite personalities. Try it out:


See a Pen Velocity.js – Easing: Spring Physics (Tester)21 by Julian Shapiro (@julianshapiro302522) on CodePen3431262320.


JavaScript Awesomeness: Scrolling


In Velocity, we can capacitate a user to corkscrew a browser to a corner of any component by flitting in scroll as Velocity’s initial evidence (instead of a properties map). The scroll authority behaves equally to a customary Velocity call; it can take options and can be queued.


Velocity(element, "scroll", duration: 1000 ;

See a Pen Velocity.js – Command: Scroll w/ Container Option24 by Julian Shapiro (@julianshapiro302522) on CodePen3431262320.


You can also corkscrew elements within containers, and we can corkscrew horizontally. See Velocity’s corkscrew documentation27 for serve information.


GSAP has ScrollToPlugin28, that offers identical functionality and can automatically relinquish control when a user interacts with a corkscrew bar.


JavaScript Awesomeness: Reverse


Both Velocity and GSAP have retreat commands that capacitate we to spur an component behind to a values before to a final animation.


In Velocity, pass in reverse as Velocity’s initial argument:


// Reverse defaults to a final call's options, that we can extend
Velocity(element, "reverse", duration: 500 );

Click on a “JS” add-on to see a formula that powers this demo:


See a Pen Velocity.js – Command: Reverse29 by Julian Shapiro (@julianshapiro302522) on CodePen3431262320.


In GSAP, we can keep a anxiety to a animation object, afterwards plead a reverse() process during any time:


var tween = TweenMax.to(element, 1, opacity:0.5);
tween.reverse();

JavaScript Awesomeness: Transform Control


With CSS animation, all renovate components — scale, translation, revolution and askance — are contained in a singular CSS skill and, consequently, can't be charcterised exclusively regulating opposite durations, easings and start times.


For abounding suit design, however, eccentric control is imperative. Let’s demeanour during a energetic renovate control that’s practicable usually in JavaScript. Click a buttons during any indicate during a animation:


See a Pen Independent Transforms32 by GreenSock (@GreenSock3319) on CodePen3431262320.


Both Velocity and GSAP concede we to away spur renovate components:


// Velocity
/* First animation */
Velocity(element, translateX: 500 , 1000);
/* Trigger a second (concurrent) animation after 500 ms */
Velocity(element, rotateZ: 45 , delay: 500, duration: 2000, queue: fake );

// GSAP
/* First animation */
TweenMax.to(element, 1, x: 500 );
/* Trigger a second (concurrent) animation after 500 ms */
TweenMax.to(element, 2, rotation: 45, delay: 0.5 );

Wrapping Up


  • Compared to CSS animation, JavaScript animation has improved browser support and typically some-more features, and it provides a some-more docile workflow for animation sequences.

  • Animating in JavaScript doesn’t entail sacrificing speed (or hardware acceleration). Both Velocity and GSAP broach peppery speed and hardware acceleration underneath a hood. No some-more messing around with null-transform hacks.

  • You don’t need to use jQuery to take advantage of dedicated JavaScript animation libraries. However, if we do, we will not remove out on performance.

Final Note


Refer to Velocity35 and GSAP’s documentation36 to master JavaScript animation.


(al, il)


Front page picture credits: NASA Goddard Space Flight Center 37.



Footnotes


  1. 1 http://codepen.io/sol0mka/full/jpecs/

  2. 2 http://codepen.io/timothyrourke/full/wojke/

  3. 3 http://codepen.io/GreenSock/full/yhEmn/

  4. 4 http://codepen.io/GreenSock/full/LuIJj/

  5. 5 http://davidwalsh.name/css-js-animation

  6. 6 http://css-tricks.com/myth-busting-css-animations-vs-javascript/

  7. 7 http://velocityjs.org

  8. 8 http://codepen.io/GreenSock/full/srfxA/

  9. 9 http://velocityjs.org

  10. 10 http://greensock.com/gsap/

  11. 11 //velocityjs.org/#dependencies”

  12. 12 http://velocityjs.org/#arguments

  13. 13 http://velocityjs.org/#uiPack

  14. 14 http://velocityjs.org/#promises

  15. 15 http://www.html5rocks.com/en/tutorials/es6/promises/

  16. 16 http://velocityjs.org/#uiPack

  17. 17 http://greensock.com/sequence-video

  18. 18 ‘http://codepen.io/GreenSock/pen/f5005e85b22ae5b7d5b1075c488cedde/’

  19. 19 ‘http://codepen.io/GreenSock’

  20. 20 ‘http://codepen.io’

  21. 21 ‘http://codepen.io/julianshapiro/pen/hyeDg/’

  22. 22 ‘http://codepen.io/julianshapiro’

  23. 23 ‘http://codepen.io’

  24. 24 ‘http://codepen.io/julianshapiro/pen/kBuEi/’

  25. 25 ‘http://codepen.io/julianshapiro’

  26. 26 ‘http://codepen.io’

  27. 27 http://velocityjs.org/#scroll

  28. 28 http://greensock.com/docs/#/HTML5/GSAP/Plugins/ScrollToPlugin/

  29. 29 ‘http://codepen.io/julianshapiro/pen/hBFbc/’

  30. 30 ‘http://codepen.io/julianshapiro’

  31. 31 ‘http://codepen.io’

  32. 32 ‘http://codepen.io/GreenSock/pen/kingu/’

  33. 33 ‘http://codepen.io/GreenSock’

  34. 34 ‘http://codepen.io’

  35. 35 http://velocityjs.org

  36. 36 http://greensock.com/docs/#/HTML5/GSAP/

  37. 37 https://www.flickr.com/photos/gsfc/6962625139

↑ Back to topShare on Twitter



Animating Without jQuery

Nenhum comentário:

Postar um comentário