Example: Using the End Event

This demonstrates how to use the end event.

Click the X in the header to fade out the element and remove it from the document once the fade completes.

The End Event

x

Click the X in the header to fade out the element and remove it from the document once the fade completes.

This is placeholder text used to demonstrate how the above animation affects subsequent content.

Setting up the HTML

First we add some HTML to animate.

<div id="demo" class="yui3-module">
    <div class="yui3-hd">
        <h3>The End Event</h3>
        <a title="fade then remove 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 and remove it from 
        the document once the fade completes.</p>
    </div>
</div>
<p>This is placeholder text used to demonstrate how the above animation affects subsequent content.</p>

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 properties to be transitioned and final values.

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

Handling the End Event

We will need a function to run when the end event fires. Note that the context of our handler defaults to anim, so this refers to our Anim instance inside the handler.

var onEnd = function() {
    var node = this.get('node'); // this === anim
    node.get('parentNode').removeChild(node); // node is an instance of Node
};

Listening for the End Event

Now we will use the on method to subscribe to the end event, passing it our handler.

anim.on('end', onEnd);

Running the Animation

Finally we add an event handler to run the animation.

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

Complete Example Source

<div id="demo" class="yui3-module">
    <div class="yui3-hd">
        <h3>The End Event</h3>
        <a title="fade then remove 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 and remove it from 
        the document once the fade completes.</p>
    </div>
</div>
<p>This is placeholder text used to demonstrate how the above animation affects subsequent content.</p> 
 

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

    var onEnd = function() {
        var node = this.get('node');
        node.get('parentNode').removeChild(node);
    };

    anim.on('end', onEnd);

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

});
</script>