Using html5 microdata to apply CSS3 transforms with jQueryPosted on: March 26, 2011

While working on a site at work, I recently came across the need to apply CSS3 transforms to elements using only the wordpress widget system. This meant that for every update to that particular section of the site, we would have to re-upload the site's stylesheet.

In an attempt to make this as simple as possible for whoever needs to update that section, I came up with the following script (be sure to run this after the DOM has loaded):

// Add transforms to elements that have the right microformat.
$('[data-transform]').each(function() {
	var _t = $(this).attr('data-transform');
	// Make sure the transformation to apply isn't empty.
	if ( _t == '') { return false; }
	// If the browser is before IE 9, and cssSandpaper is in use, use it's transform.
	if ($.browser.msie && $.browser.version.substr(0,1) < 9 && cssSandpaper) {
		cssSandpaper.setTransform(this, _t);
	} else {
		$(this).attr('style', '-moz-transform:'+_t+';-ms-transform:'+_t+';-webkit-transform:'+_t+';transform:'+_t+';');
	}
});

There you have it, I can now apply a transform by just adding an HTML5 custom data attribute. In the below example, I apply a 10 degree rotation to a div:

<div data-transform="rotate(10deg)">
    <!-- content here -->
</div>

... another example where I skew the div by 10 degrees:

<div data-transform="skew(10deg)">
    <!-- content here -->
</div>

You could of course use this concept in any way you like, for example, I ended up creating a data attribute that lets me make a whole div clickable (without having to sacrifice semantics by wrapping the whole thing in an anchor tag). I did this by adding a data-href attribute to store the link to go to, and an optional data-target attribute for the target (_blank, _self, etc.).

You'll also note that I've made use of Zoltan Dulac's great cssSandpaper JS library that allows these transforms to work in IE as well. If you haven't looked into it, I highly recommend you do.