‘animateToSelector’ jQuery plugin

This is an experimental jQuery plugin which animates according to a CSS selector. The plugin looks up the selectors in the StyleSheet/s of a document and then animates according to the specified properties. It’s similar to jQuery UI’s ‘classTransitions‘ although it’s much more capable; not only can it animate to classes but any selector, as long as it’s specified in the CSS.

Probably the most useful thing about this plugin, and the main reason I created it, is that it can animate to pseudo classes such as ‘:hover’. This means the plugin can animate your hover states too; and because they’re specified in the CSS they won’t fail when JavaScript is disabled. This is what progressive enhancement is really about!

See demonstration and documentation (& download)!

With the plugin I’ve included Resig’s color extension so not only can it animate size properties like ‘width’, ‘left’ or ‘padding’ but it can also handle color properties like ‘border-color’, ‘color’ or ‘background-color’.

It’s not a simple “call n’ go” type of plugin, you do need to specify a selector (which must exist in the document’s StyleSheet/s) and you also need to specify properties to retrieve from that selector. Here’s an example of how one might call the plugin:

$('#navigation a').animateToSelector({
 
    // One or more selectors; must exist
    // within the CSS StyleSheet. First one
    // has precedence ([0]):
    selectors: ['#navigation a:hover'],
 
    // You need to specify what properties to
    // animate within the selector:
    properties: [
        'background-color',
        'padding-left',
        'color'
    ],
 
    // An optional setting, without this setting
    // the animation proceeds straight away:
    events: ['mouseover', 'mouseout'],
 
    // Duration of animation:
    duration: 300
 
});

The above code would make all anchors within #navigation animate to the specified properties of the specified selector onMouseOver and then will revert the animation onMouseOut. So, the plugin get’s the properties from here:

#navigation a:hover {
    padding-left: 20px;
    background-color: #bdd70d;
    color: #222;
}

The name of the plugin can be misleading – when you pass selectors into the ‘selectors’ array as a setting you are not selecting elements within the DOM – the plugin doesn’t even touch the DOM – it simply scans through the StyleSheets for the corresponding selectors and properties.

If you missed it earlier, here’s a link to the demo and documentation. There are a few issues (not bugs) with the implementation; it works in all modern browsers (only tested on Windows XP though). Comments and crits welcome!

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!