cssHooks in jQuery 1.4.3

09 Nov 2010

jQuery 1.4.3 brought us a complete rewrite of the CSS module. The main focus of this rewrite was to add extensibility. Along with some nice speed-ups in getting styles, the CSS module of jQuery now let you extend the functionality of .css() and .animate().  It allows this by adding cssHooks.

cssHooks allow you to “hook” in to how jQuery gets and sets css properties.  This means that you could create a cssHook to help normalize differences between browsers, or to add some missing functionality from the stock jQuery.fn.css().

Brandon Aaron has been doing some work, along with others, to create a collection of cssHooks.  They currently have:

  • margin and padding
  • backgroundPosition, backgroundPositionX, backgroundPositionY
  • boxShadow, boxShadowColor, boxShadowBlur, boxShadowX, boxShadowY

And I am sure there more to come.

Defining a new cssHook is very easy

	$.cssHooks['cssproperty'] = {
		get: function( elem, computed, extra ) {
			// Handle getting the css property here
		},
		set: function( elem, value ) {
			// Handle setting the css value here
		}
	};

Very simple and easy. To allow your new cssHook to be used with .animate() all it takes is (for simple number value animations):

	$.fx.step [ "cssproperty" ]  = function( fx ) {
		$.cssHooks [ "cssproperty" ].set( fx.elem, fx.now + fx.unit);
	};

Will be interesting to see what other cssHooks show up.