Example: Animating Colors

This demonstrates how to animate color attributes.

Mouse over the link to begin the animation.

hover me

Setting up the HTML

First we add some HTML to animate.

<a href="#" id="demo">hover me</a>

Creating the Anim Instance

Now we create an instance of Y.Anim, passing it a configuration object that includes the node we wish to animate and the to attribute containing the final properties and their values.

Adding a from attribute allows us to reset the colors onmouseout using the reverse attribute, which we will see below.

var node = Y.one('#demo');

var anim = new Y.Anim({
    node: node,
    from: {
        backgroundColor:node.getStyle('backgroundColor'),
        color: node.getStyle('color'),
        borderColor: node.getStyle('borderTopColor')
    },

    to: {
        color: '#fff',
        backgroundColor:'#FF8800',
        borderColor: '#BA6200'
    },

    duration:0.5
});

Running the Animation

Next we need a handler to run when the link is moused over, and reverse when moused out.

var hover = function(e) {
    var reverse = false;
    if (anim.get('running')) {
        anim.pause();
    }
    if (e.type === 'mouseout') {
        reverse = true;
    }
    anim.set('reverse', reverse);
    anim.run();
};

Listening for the Events

Finally we add an event handler to run the animation.

node.on('mouseover', hover);
node.on('mouseout', hover);

Complete Example Source

<a href="#" id="demo">hover me</a>

<script type="text/javascript">
YUI().use('anim', function(Y) {
    var node = Y.one('#demo');

    var anim = new Y.Anim({
        node: node,
        from: {
            backgroundColor:node.getStyle('backgroundColor'),
            color: node.getStyle('color'),
            borderColor: node.getStyle('borderTopColor')
        },

        to: {
            color: '#fff',
            backgroundColor:'#FF8800',
            borderColor: '#BA6200'
        },

        duration:0.5
    });

    var hover = function(e) {
        var reverse = false;
        if (anim.get('running')) {
            anim.pause();
        }
        if (e.type === 'mouseout') {
            reverse = true;
        }
        anim.set('reverse', reverse);
        anim.run();
    };
    node.on('mouseover', hover);
    node.on('mouseout', hover);

});

</script>