Button Icon Option Shortcut

Providing a simpler way for the rest of your application to set button icons.

by Adam Boduch

HTML

<button>Done</button>

CSS

body {
    font-size: 0.8em;
}

JavaScript

(function( $ ) {

    // Extending the button widdget with a simplified icon option.
    $.widget( "app.button", $.ui.button, {
        
        // The button constructor.
        _create: function() {
            
            this._super();
            
            // If the simplified "icon" option was set, set it as the "primary"
            // icon.
            if ( this.options.icon ) {
                this.option( "icons.primary", this.options.icon );    
            }
            
        },
        
        // Called when an option is set.
        _setOption: function( key, value ) {
        
            // If the simplified "icon" option was set, set it as the "primary"
            // icon.
            if ( key === "icon" ) {
                return this.option( "icons.primary", value );    
            }
            
            this._superApply( arguments );
        
        }
        
    });
    
    // Use the new "icon" option to initially set the button icon. On
    // click, change the "icon" option value.
    $( "button" ).button({
        icon: "ui-icon-check"
    }).on( "click", function( e ) {
        $( this ).button( "option", "icon", "ui-icon-notice" );    
    });
    
})( jQuery );