jQuery: binding animation data to elements with JSON

A simple way to create a more concise jQuery code is to separate animation data (i.e. CSS properties and values) from our main code and to bind such data to the elements where it belongs. JSON offers an efficient solution to this problem. Simply put, we create a custom HTML5 data attribute and we store a JSON string (well-formed) within this attribute. Then we convert back this string to a JSON object by using jQuery's $.parseJSON(). Let's see how.

First of all, our attribute's value must be either HTML-compliant or JSON-compliant:

<div id="test" data-anim='{"width":500,"height":500,"top":100}'></div>

If you don't provide a valid JSON string, jQuery will return an error. Here's how we can use this custom attribute:

$('#test').click(function() {
    var data = $(this).attr('data-anim');
    var anims = $.parseJSON(data);
    $(this).animate(anims, 1000);
});​

See how this code is terse and short instead of the traditional way of creating animations? A single example is nothing: imagine that you have to create a web application with a lot of pages and with a pletora of jQuery effects on each page. I experienced this problem myself (here). The final code was bloated and redundant.

If you work also on the server-side, you can actually design a CMS interface or even a simpler hook mechanism that allows you to dynamically create these data attributes.

I've used $.parseJSON() because it works in a cross-browser fashion. Obsolete browsers have problems only with recognizing unknown elements, but attributes are treated as normal attribute nodes (without any special meaning, though). If you have problems with data attributes, you can still fallback to plain HTML class attributes.

You can see the demo below.

Demo

Live demo

Back to top