Should I use CSS or JavaScript for animation

0800 156 0777

Should I use CSS or JavaScript for animation

When you are creating a web page, you quite often want a little animation, maybe a rollover effect, or a small ad or banner. The question these days is which language will you do it in - css or javascript?

You can of course do it in either, however here are a few notes to help you decide which to choose…

If you choose CSS…

Pros:

  • CSS is simpler to learn - if you are designer and do not like or want or have the time to learn code, using css is certainly quicker and easier to learn.
  • You can animate virutally any css property - colour, position, width, height, etc, etc
  • You can produce a simple animation very quickly
  • With the right CSS your animation can be very fast and fluid - very smooth

Cons:

  • CSS is not very flexibile as regards events and control structures - like loops etc
  • It has loops but you do not have the variety that JavaScripts has - i.e. while, for, etc
  • It is hard to create complex structures - games etc. Possible, but hard.
  • CSS is a newer language than JavaScript so cross-compatibilty can be an issue. Some commands may not work in certain browsers, or you may need to duplicate code and prefix them to make sure they work for various browsers. This is getting better, but it is still something to be aware of.

If you choose JavaScript:

Pros:

  • It has more events and control structures so it is easier to create more sophisticated code and longer control structures
  • There are a wide range of JavaScript libraries out there that you can leverage for more advanced functionality

Cons

  • JavaScript is harder to learn
  • CSS is often faster than JavaScript
  • JavaScript can be disabled in the browser, CSS can't (yet).

In summary then, generally (but not always)  CSS is faster than JavaScript - but things are changing all the time (some CSS commands are GPU accelerated so can be really fast with modern browsers). JavaScript has lots of functions, control structures and events so you can really control what you do and when, this is why it can take longer to create things using JavaScript.

So there is no hard and fast rule - these days I generally see them both being used in a project. CSS does the animation, but it is JavaScript that does the triggering, i.e. click hrer and this happens - the click is JavaScript but it triggers CSS to do the animation.

Oh and another thing - you can disable JavaScript, but you cannot (yet) disable CSS.