Example: Animating XY Position

This demonstrates how to animate the xy position of an element.

Click anywhere on the gray box below and the little orange box will move to the click position.

Setting up the HTML

First we add some HTML to animate.

<div id="demo-stage">
    <span id="demo"></span>
</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. We will set the to attribute later when then animation runs.

var anim = new Y.Anim({
    node: '#demo',
    duration: 0.5,
    easing: Y.Easing.elasticOut
});

Changing Attributes

Next we need a click handler to set the to attribute for the xy behavior and run the animation.

var onClick = function(e) {
    anim.set('to', { xy: [e.pageX, e.pageY] });
    anim.run();
};

Running the Animation

Finally we add an event handler to run the animation when the document is clicked.

Y.one('document').on('click', onClick);

Complete Example Source

<div id="demo-stage">
    <span id="demo"></span>
</div>

<script type="text/javascript">
YUI().use('anim', function(Y) {
    var anim = new Y.Anim({
        node: '#demo',
        duration: 0.5,
        easing: Y.Easing.elasticOut
    });

    var onClick = function(e) {
        anim.set('to', { xy: [e.pageX, e.pageY] });
        anim.run();
    };
    
    Y.one('#demo-stage').on('click', onClick);

});

</script>