Menu Search
Jump to the content X X
Smashing Conf New York

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Animating Without jQuery

There’s a false belief in the web development community that CSS animation is the only performant way to animate on the web. This myth has coerced many developers to abandon JavaScript-based animation altogether, thereby (1) forcing themselves to manage complex UI interaction within style sheets, (2) locking themselves out of supporting Internet Explorer 8 and 9, and (3) forgoing the beautiful motion design physics that are possible only with JavaScript.

Reality check: JavaScript-based animation is often as fast as CSS-based animation — sometimes even faster. CSS animation only appears to have a leg up because it’s typically compared to jQuery’s $.animate(), which is, in fact, very slow. However, JavaScript animation libraries that bypass jQuery deliver incredible performance by avoiding DOM manipulation as much as possible. These libraries can be up to 20 times faster than jQuery.

So, let’s smash some myths, dive into some real-world animation examples and improve our design skills in the process. If you love designing practical UI animations for your projects, this article is for you.

Why JavaScript? Link

CSS animations are convenient when you need to sprinkle property transitions into your style sheets. Plus, they deliver fantastic performance out of the box — without your having to add libraries to the page. However, when you use CSS transitions to power rich motion design (the kind you see in the latest versions of iOS and Android), they become too difficult to manage or their features simply fall short.

Ultimately, CSS animations limit you to what the specification provides. In JavaScript, by the very nature of any programming language, you have an infinite amount of logical control. JavaScript animation engines leverage this fact to provide novel features that let you pull off some very useful tricks:

Note: If you’re interested in learning more about performance, you can read Julian Shapiro’s “CSS vs. JS Animation: Which Is Faster?5” and Jack Doyle’s “Myth Busting: CSS Animations vs. JavaScript6.” For performance demos, refer to the performance pane7 in Velocity’s documentation and GSAP’s “Library Speed Comparison8” demo.

Velocity and GSAP Link

The two most popular JavaScript animation libraries are Velocity.js9 and GSAP10. They both work with and without jQuery. When these libraries are used alongside jQuery, there is no performance degradation because they completely bypass jQuery’s animation stack.

If jQuery is present on your page, you can use Velocity and GSAP just like you would jQuery’s $.animate(). For example, $element.animate({ opacity: 0.5 }); simply becomes $element.velocity({ opacity: 0.5 }).

These two libraries also work when jQuery is not present on the page. This means that instead of chaining an animation call onto a jQuery element object — as just shown — you would pass the target element(s) to the animation call:

/* Working without jQuery */

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

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

As shown, Velocity retains the same syntax as jQuery’s $.animate(), even when it’s used without jQuery; just shift all arguments rightward by one position to make room for passing in the targeted elements in the first position.

GSAP, in contrast, uses an object-oriented API design, as well as convenient static methods. So, you can get full control over animations.

In both cases, you’re no longer animating a jQuery element object, but rather a raw DOM node. As a reminder, you access raw DOM nodes by using document.getElementByID, document.getElementsByTagName, document.getElementsByClassName or document.querySelectorAll (which works similarly to jQuery’s selector engine). We’ll briefly work with these functions in the next section.

Working Without jQuery Link

(Note: If you need a basic primer on working with jQuery’s $.animate(), refer to the first few panes in Velocity’s documentation.11)

Let’s explore querySelectorAll further because it will likely be your weapon of choice when selecting elements without jQuery:

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 the divs contained by "main"

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

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

/* Animate all divs at 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 element objects, you may be wondering how we can chain animations back to back, like this:

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

In Velocity, you simply call animations one after another:

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

Animating this way has no performance drawback (as long as you cache the element being animated to a variable, instead of repeatedly doing querySelectorAll lookups for the same element).

(Tip: With Velocity’s UI pack, you can create your own multi-call animations and give them custom names that you can later reference as Velocity’s first argument. See Velocity’s UI Pack documentation12 for more information.)

This one-Velocity-call-at-a-time process has a huge benefit: If you’re using promises13 with your Velocity animations, then each Velocity call will return an actionable promise object. You can learn more about working with promises in Jake Archibald’s article14. They’re incredibly powerful.

In the case of GSAP, its expressive object-oriented API allows you to place your animations in a timeline, giving you control over scheduling and synchronization. You’re not limited to one-after-the-other chained animations; you can nest timelines, make animations overlap, etc:

var tl = new TimelineMax();
/* GSAP tweens chain by default, but you can specify exact insertion points in the timeline, including relative offsets. */
tl
  .to(element, 1, { opacity: 0.5 })
  .to(element, 1, { opacity: 1 });

Footnotes Link

  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 http://velocityjs.org/#arguments
  12. 12 http://velocityjs.org/#uiPack
  13. 13 http://velocityjs.org/#promises
  14. 14 http://www.html5rocks.com/en/tutorials/es6/promises/
SmashingConf New York

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

Overview of this article


Page 1/2»

↑ Back to top Tweet itShare on Facebook

Julian Shapiro is a startup founder and a developer. His first startup, NameLayer, was acquired by Techstars. His current focus is advancing motion design on the web. Follow him for tweets on UI animation: @Shapiro.

  1. 1

    CSS-based animations that only trigger compositing can typically proceed without main thread intervention so should you get a GC pause or some other main thread halt, the CSS-based animation can continue. This is where the “myth” has originated and that assertion is not incorrect (and hence not a myth), but it is an incomplete picture.

    What matters is _what exactly_ you animate with either JS or CSS, as that will govern your performance characteristics. If your animation changes a property that triggers layout or paint (which many do: http://csstriggers.com) it will be difficult to achieve 60fps, particularly on mobile. My hope is that in the future that’s not the case, but today that’s true.

    In any case it’s nice to see pretty animations delivered through Velocity or GSAP. I still get frustrated that jQuery animates without requestAnimationFrame, but I guess that’s a topic for another day! :)

    28
  2. 2

    I’ll give it a try, good article :)

    1
  3. 3

    Nice comparison and examples.

    I’m using GSAP’s TweenMax for most projects already mainly because of IE8 support. This goes for complex animations as well as necessary animations. If we’re talking about simple fade-in effects or small (but beautiful) transitions, I always use CSS only.

    I never tried velocity.js but I’ve read quite a few good things about it. I don’t see a need to try it / switch right now though.

    I’d love to see a detailed article about GSAP’s TimelineMax library.

    4
  4. 4

    I’ve done my share of animations with GSAP and I have to admit I love it. Lewis above is correct to a point, yet when I’m writing my animations, I have to ask myself whether it’s prudent to have them split in two, some in css and some in js. On top of that, the company I work for is a major ebay seller and ebay isnt exactly friendly when it comes to js libraries. That means we’re forced to load at least the very basic (common) animations from our library with css, whether we like it or not.

    6
    • 5

      Oh no you’re absolutely right, I’m not actually voting in one direction or another. I generally think declarative animations are best, but I also think if you’ve started down the JS animation path for whatever reason then your sanity is probably best served by sticking with it entirely! Mix ‘n’ match can get very hairy.

      4
  5. 6

    This is an awesome article. These libraries really have the ability to bootstrap meaningful interactions.

    2
  6. 7

    Dmitri Tcherbadji

    September 5, 2014 3:47 am

    Great article and a reminder (as many have already pointed out above) that “it all depends”.

    Personally I try to stray away from using too many libraries and plug-ins as much as possible. It helps to free up some resources for the user and avoid managing too many assets that might be changed or updated elsewhere. But if the project requires advanced animation, CSS is definitely not the best way – it simply isn’t made for complex, combined movements or physics-involved motions shown above. It would make the most sense to use either of these libraries and enjoy a breeze of fast, easy coding resulting in beautiful motion.

    Most of my projects involve very straight-forward interactions however, where animation is more of a “helper” that guides the user a little better than a static element. In this case I think it’s best to just use CSS3 transitions since objective is usually simple enough as “move A to B”. Some browsers will not gel well with it of course, like IE8. But neither will they render my rounded borders – and I really do not intend to use another plugin just to make that happen.

    Making things work on really really old, crappy browsers just like they do in a new Chrome release is extremely counter-productive. Things should work there of course – if the data shows that the users demand that. But they do not have to be animated, they do not have to be very pretty. Because adding weight to the project in order to do fancy things will punish me, punish the “modern” users and will punish the older browsers’ users. Advanced graphics will slow down their dusty boxes (besides, anyone who uses IE8 by now is probably used to ugly web already).

    6
    • 8

      I guess you have the luxury of not supporting outdated browsers like IE <9.

      Most of us have to support legacy browsers, that's why libs like jQuery were built in the first place.

      -2
  7. 9

    Otto Nascarella

    September 5, 2014 4:40 pm

    Nice work with Velocity!

    What about callbacks with this new syntax?

    1
    • 10

      Julian Shapiro

      September 5, 2014 6:27 pm

      Thanks!

      Same as always; pass in a `complete` or `begin` callback. Check the docs for both libs — very straight-forward.

      1
  8. 11

    Nice! Been just digging into this topic last week – because I prefer Vanilla Javascript over excessive framework / library bloat. Also, you so readily forget about how to actually get things done in Javascript, while always having to goof around with jQuery all day.

    cu, w0lf.

    1
  9. 12

    This is very Nice Articles. The Examples for velocity has been impressed. :)

    2
  10. 13

    I haved used GSAP since its beta period and I must admit I cannot change it with anything. I has allowed me to produce extremely complex animations with great performance and in a just a few lines of code. JS animating is more close to me because I come from a strictly code based background and it feels more natural to declare things in an object oriented way. However I have witnessed some extremely well done animations that were made via CSS.
    It is only beneficial to all to have more options. Also well done on the article it was an easy read.

    0
  11. 14

    It’s worth noting that document.querySelectorAll does not return an array. It returns a non-live NodeList

    2
  12. 15

    Daniel Schwarz

    September 9, 2014 3:33 pm

    Nice article. I’ve always been familiar with transit.js, and still don’t have a reason to switch as I’m very happy with it and use it for a lot of websites, http://airwalk-design.com being one of them.

    It’s lightweight and useful for chaining animations, but if it’s something simple, CSS is always the method I would use, especially if you can take the time to create your own animation mixins for LESS (only compile what you need).

    0
  13. 16

    There are far more advanced js libs:
    http://d3js.org/
    http://threejs.org/

    -1
  14. 18

    La Casita Del Cuco

    September 13, 2014 8:01 am

    But Jquery animation do not work on mobiles! Or is that a myth as well? With growing mobile use an important point to take in consideration.

    0
  15. 19

    Great Post. Thanks

    1
  16. 20

    Good comparisons.

    0
  17. 21

    Very simple compare between jQuery (or native js) and GSAP:

    GSAP is able to animate to an other position while it’s changing its background color at the same time. During a tween of GSAP you can call a function to handle some data, so you can build-in a tracker. Plus during the animation you can pause and resume it or increasing/decreasing time.

    jQuery is unable to do anything like that, and ofcourse.. tweening (‘inbetweening’) looks 10 times better than normal position change (jQuery animate, or own javascript loop).

    Velocity is also outdated agains GSAP.

    0
  18. 22

    Very informative article, tough choice between the two. I like them both, I wish that Velocity had better docs and examples. Greensock wins out in the learning resource department

    0
  19. 23

    Great article, tx!

    Stumble upon while i was looking for a tutorial, some inspiration to make something like rw.runnersworld.com/sub-2/ for a quiz. Where the page transistion happens when you answer a question.

    Any ideas, tips where i can find some inspiration/tutorials?

    regards

    0
  20. 24

    Good Article, But CSS3 object-fit property is good for animation http://www.devtantra.com/273/object-fit-css3/

    -5

↑ Back to top