Thursday, February 27, 2014

Animating Position Changes

The jQuery UI position utility is about doing math. Specifically, it's performing translations for us, from human-readable position coordinates, into something the browser can understand. Obviously, this is a powerful tool to have at our disposal while doing UI development. I use it all the time. And not just to position elements as the page first loads, also in response to user events. It's this latter scenario where I would like to animate the change in position. The position utility provides an entry point for us to do that.

This example illustrates how the using option of the position utility works. It accepts a callback function, and passes some useful data to that function. For example, using this code, we can animate the change in position using animate().

$( "button" ).button().click(function( e ) {
    $( "#moveme" ).position({
        my: "right bottom",
        at: "right bottom",
        of: "body",
        using: function( pos, ui ) {
     ui.element.element.animate( 
         pos, { 
             duration: 800,
             easing: "easeOutExpo"
         });
        }
    });
});

The pos argument in the callback function is the new position coordinates of the element being positioned. These values are used by position() to actually change the CSS properties. Except, when you pass in a using callback function, position just computes the CSS changes, and doesn't actually set them. It just passes them to our function, which is incredibly helpful, because now I can animate those changes as I wish. I could even interpret the values differently if I chose to do so. However, I do not — simply animating the position change is useful enough for me.