Thursday, November 28, 2013

jQuery UI: Dialog Close Button Text

By default, the jQuery UI dialog widget places a close button on the right-hand side of the title bar. In past versions, this has just been a strewn-together mess of elements and events. Now it uses the button widget, which for obvious reasons, makes things a little easier to handle. Like when you only want text displayed, and not the close icon.

We can implement our close button customization logic in the create event, since this is triggered as soon as the dialog is ready for action. For example, the end result looks something like this.


Let's take a peek at the code added to the create event callback function that changes the close button.

var $parent = $( this ).parent(),
    $button = $parent.find( ".ui-dialog-titlebar-close" ),
    $title = $parent.find( ".ui-dialog-title" );
        
$title.css( { width: "auto", margin: "0.44em 0" } );
        
$button.removeClass( "ui-dialog-titlebar-close" )
       .css( "float", "right" )
       .button( "option", {
           icons: {primary: false},
           text: true,
           label: "Close"
       });

The function starts off with three variables. The $parent variable is the actual dialog element. Keep in mind that we have to use .parent() here instead of this because the element is wrapped when the dialog is instantiated. The $button variable is the button on the right side of the title bar and the $title variable is the text on the left side of the title bar.

Starting with $title, we need to adjust the width and the margin properties. The title initially has a width that prevents us from re-positioning the button. So we get rid of it by setting it to auto. The margin is adjusted only slightly, relative to it's initial value. This is done in anticipation of the button height change is applied, due to it displaying text.

And that's what happens next. The first action item for fixing the button involves removing the ui-dialog-titlebar-close class. This class defines several layout CSS properties that are really only useful for icon-only buttons. Next, we position the button to the right of the title bar by setting float to right. Last but not least, we have a few button widget options to change. The icons option says that there should be no primary icon — there is no other way to hide the button icons. The text option is initially false — we set it to true because we want the text displayed. Lastly, the button label is applied.

Why go to all this trouble, just to reconfigure the close button that's already there? Why not just remove the default button and add our own? Well, we'd probably end up writing twice as much code. This way, we're not concerned about element removal or event binding.

No comments :

Post a Comment