Native JavaScript Equivalents of jQuery Methods: CSS and Animation

Craig Buckler
Share

Do You Really Need jQuery? Sometimes — especially if you want to support IE6/7/8 using jQuery 1.x. However, modern browser APIs now provide much of the functionality we take for granted in jQuery. In this article, we’re going to look at methods related to CSS.

Class Manipulation

One of the most common jQuery tasks is applying a class to a specific element:

$("#myelement").addClass("myclass");

We can achieve the same thing in native JavaScript:

document.getElementById("myelement").className = "myclass";

This isn’t quite the whole story:

  1. jQuery can apply the class to any number of nodes.
  2. jQuery appends the new class to existing class definitions, but the native example will overwrite them.

In native JavaScript, the className property is simply a string. We therefore need a function to replicate how jQuery works, e.g.

function addClass(node, class) {
	if (!node.length) node = [node];
	for (var n = 0, m = node.length; n < m; n++) {
		if ((" " + node[n].className + " ").indexOf(" "+class+" ") >= 0) {
			node.className += " " + class;
		}
	}
}
// apply myclass to all nodes
addClass(document.getElementById("myelement"), "myclass");

While this code is smaller and faster than jQuery, we’re replicating what’s already available in the library — there’s little point.

Fortunately, modern browsers now offer a new classList property which implements a DOMTokenList — an array-like collection of all classes applied to a node. The following properties are available:

  • length — the number of class names applied
  • item(index) — the class name at a specific index
  • contains(class) — returns true if a node has that class applied
  • add(class) — applies a new class to the node
  • remove(class) — removes a class from the node
  • toggle(class) — removes or adds a class if it’s applied or not applied respectively

We can use this in preference to the clunkier className property:

document.getElementById("myelement").classList.add("myclass");

classList is supported by most browsers except IE9. Fortunately, a couple of shims are available which could be conditionally loaded in that browser.

Style Manipulation

jQuery provides a number of methods to apply specific styles, e.g.

$("#myelement").css({
	color: "#c00",
	backgroundColor: "#eee",
	width: "200px",
	height: "100px",
	borderColor: "#f00"
});

The native equivalent:

var m = document.getElementById("myelement"), c = m.style;
c.color = "#c00";
c.backgroundColor = "#eee";
c.width = "200px";
c.height = "100px";
c.borderColor = "#f00";

Over 10,000 iterations using cached selectors, the jQuery code executed in 6,670ms. Native JavaScript took 330ms — it was 20x faster.

Of course, you shouldn’t use either unless a value needs to be calculated in some way. It’s more efficient to define a class of styles in CSS then apply its name to the element.

Animation

jQuery offers various animated effects out of the box including sliding and fading. Native JavaScript can be faster but none of that matters: CSS3 animation trounces both.

I was initially skeptical about CSS3 animation. It can never offer fine-grained control (such as stopping an animation after N frames) and trespasses on JavaScript’s behavioral responsibilities. However, the benefits more than outweigh the drawbacks:

  1. CSS3 animation is handled by the browser; it will always be faster than JavaScript execution.
  2. CSS3 animation is easier to use and requires significantly less code.
  3. CSS3 offers effects such as 3D transformations which would be impractical — if not impossible — in JavaScript alone.

IE9 and below won’t show the effects but they can degrade gracefully and IE10 should be the dominant version within a few months.

The CSS3 genie will never go back in the lamp. If you’re still using jQuery or JavaScript for DOM animation in modern browsers, you’re probably wasting your time.

That said, JavaScript can be used to react to CSS3 animations when they start, stop or proceed to the next iteration using animationstart, animationend and animationiteration accordingly. For more information, refer to How to Capture CSS3 Animation Events in JavaScript.

In my next article, we’ll finish the series by looking at events, Ajax and utility functions.