Adding Buttons To The Dialog Titlebar

Extending the jQuery UI dialog widget by adding an icon button option. This option accepts an array of buttons to add to the titlebar.

HTML

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/start/jquery-ui.css">
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

    
<div id="dialog" title="Dialog Title">
    <p>Basic dialog content</p>
</div>

<p class="ui-widget-content
  ui-state-default ui-helper-clearfix">
  <span style="float: left; margin-right: 0.5em;"
    class="ui-icon ui-icon-jquery">icon</span>
  ui-icon-jquery
</p>

CSS

body {
    font-size: 0.8em;
}

JavaScript

(function( $, undefined ) {

    // Extends the dialog widget with a new option.
    $.widget( "app.dialog", $.ui.dialog, {
    
        options: {
            iconButtons: []
        },
    
        _create: function() {
    
            // Call the default widget constructor.
            this._super();
    
            // The dialog titlebar is the button container.
            var $titlebar = this.uiDialog.find( ".ui-dialog-titlebar" );
    
            // Iterate over the "iconButtons" array, which defaults to
            // and empty array, in which case, nothing happens.
            $.each( this.options.iconButtons, function( i, v ) {
    
                // Finds the last button added. This is actually the
                // left-most button.
                var $button = $( "<button/>" ).text( this.text ),
                    right = $titlebar.find( "[role='button']:last" )
                                     .css( "right" );
    
                // Creates the button widget, adding it to the titlebar.
                $button.button( { icons: { primary: this.icon }, text: false } )
                       .addClass( "ui-dialog-titlebar-close" )
                       .css( "right", ( parseInt( right ) + 22) + "px" )
                       .click( this.click )
                       .appendTo( $titlebar );
    
            });
    
        }
    
    });
    
    $(function() {
    
        // Pass some custom icon buttons to the dialog.
        $( "#dialog" ).dialog({
            iconButtons: [
                {
                    text: "Search",
                    icon: "ui-icon-search",
                    click: function( e ) {
                        $( "#dialog" ).html( "<p>Searching...</p>" );
                    }
                },
                {
                    text: "Add",
                    icon: "ui-icon-plusthick",
                    click: function( e ) {
                        $( "#dialog" ).html( "<p>Adding...</p>" );
         ...