Friday, March 28, 2014

Animating jQueryUI Slider Positions

The jQuery UI slider widget has an animate option that's a little misleading. It doesn't animate the slider handle when the widget is first instantiated. There's no animation when the user physically drags the slider handle. The only difference the animation option makes, when turned on, is it animates the handle when the user clicks the slider bar.

For example, let's say the slider handle is at 25%. The user then clicks somewhere around 75%. If the animate option is turned on, the handle will "glide" to the new position, producing and subtly-pleasing effect. What would be really cool is if we could animate the initial position of the handle. That is, if the initial value was 50%, the handle would animate from 0 to the 50% position.

We can't do that, however, without implementing a custom slider extension because there are constraints in place that temporarily disable animations. This is to prevent excessive animating while the user is dragging the handle back and forth. Here's an example of how to override that behavior when the slider is first created.

$.widget( "app.slider", $.ui.slider, {

    _create: function() {
        
        var value = this.options.value,
            animate = this.options.animate;
        
        if ( value > 0 && animate ) {
        
            this.options.value = 0;
            this._super();
            
            this.options.value = value;
            this._refreshValue();
            
        } else {
        
            this._super();
            
        }
        
    }

});

Here, we're overriding the slider constructor so that we can animate the initial slider values. First, we grab the value of the slider and store it in the value variable. If the value is greater than 0 and the animate option is turned on, then we reset the value option to 0 and call the default slider constructor. This sets everything up for the widget to be used — no animation has taken place. We've ensured that the handle is located at the animation starting line by resetting the value option to 0.

Next, the value is restored, and making a call to the _refreshValue() method will animate the handle for us. The reason this works is that the _refreshValue() method has no constraints about temporarily disabling animations.