Wednesday, January 15, 2014

Value and Remaining Labels For Progressbars

The jQuery UI progressbar widget doesn't display a value label. It's easy enough to introduce one, however, and it's often worthwhile to do so. While the visual representation of the progressbar widget works well for conveying the value as a percentage, it's useful to know the actual value. What does 35% translate to, in other words? So the used value is one part, the remaining value is another. It would be nice if the progressbar could show both these numbers as labels.

The progressbar has a max option, and a value option. The value is the used part, while the max - value is the remaining part. Users care about both. In fact, they may care more about what's remaining. Here's an example of how to customize the progressbar widget, adding a new labels option.

The two buttons in the simply increment and decrement the progressbar value, so you can watch the two labels update. The bulk of our progressbar customization takes place in the _refreshValue() method, which looks like this.

_refreshValue: function() {
        
    this._super();
            
    if ( !this.options.labels ) {
        return;    
    }

    this.element.addClass( "ui-progressbar-labels" )
                .find( "span" ).remove();
            
    $( "<span/>" ).text( this.options.max - this.value() )
                  .prependTo( this.element );            
            
    $( "<span/>" ).text( this.value() )
                  .prependTo( this.element );

}

The first thing that happens inside _refreshValue() is a call to _super(). This method calls the original implementation, and since we have no need to interfere with that, we get it out of the way. Next, we perform a short-circuit exit from the method if the labels options isn't true.

Next, the progressbar element gets the ui-progressbar-labels class applied to it. This will apply the CSS necessary to align the two spans we add to the progressbar div. Note, that the line-height has to be the same as the height of the progressbar div. We also remove any span elements that may have been added already.

Last but not least, we compute the label values, add them to their span elements, and add those to the progressbar. The value label to the left, the remaining label to the right.

No comments :

Post a Comment