Example: Basic Animation

This demonstrates how to animate the opacity of an element.

Click the X in the header to fade out the element.

Basic Animation

x

Click the X in the header to fade out the element.

Setting up the HTML

First we add some HTML to animate.

<div id="demo" class="yui3-module">
    <div class="yui3-hd">
        <h3>Basic Animation</h3>
        <a href="remove.php?id=#demo" title="fade out element" class="yui3-remove"><em>x</em></a>
    </div>
    <div class="yui3-bd">
        <p>Click the X in the header to fade out the element.</p>
    </div>
</div>

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.

var anim = new Y.Anim({
    node: '#demo',
    to: { opacity: 0 }
});

Handling the Click Event

Clicking the toggle control should start the animation, so we'll need to handle that click, including preventing the default action of following the url.

var onClick = function(e) {
    e.preventDefault();
    anim.run();
};

Running the Animation

Finally we add an event listener to run the animation.

Y.one('#demo .yui3-remove').on('click', onClick);

Complete Example Source

<div id="demo" class="yui3-module">
    <div class="yui3-hd">
        <h3>Basic Animation</h3>
        <a href="remove.php?id=#demo" title="fade out element" class="yui3-remove"><em>x</em></a>
    </div>
    <div class="yui3-bd">
        <p>Click the X in the header to fade out the element.</p>
    </div>
</div>


<script type="text/javascript">
YUI().use('anim', function(Y) {
    var anim = new Y.Anim({
        node: '#demo',
        to: { opacity: 0 }
    });

    var onClick = function(e) {
        e.preventDefault(); 
        anim.run();
    };

    Y.one('#demo .yui3-remove').on('click', onClick);

});

</script>