Default Widget Options

Creating custom jQuery UI widgets for the sole purpose of providing a new set of default options.

by Adam Boduch

HTML

<div class="error-dialog" title="Error">
    <p class="ui-state-error"></p>
</div>

<a href="#" class="break-stuff ui-widget">Trigger Error</a>

CSS

body {
    font-size: 0.8em;
}

.ui-dialog-content p.ui-state-error {
    background: none;
    border: none;
}

JavaScript

(function( $ ) {

    // Creates a specialized widget that extends the dialog widget,
    // providing some default options.
    $.widget( "app.error", $.ui.dialog, {
        options: {
            modal: true,
            autoOpen: false,
            width: 450,
            height: 100,
            position: {
                my: "top",
                at: "top+10",
                of: window
            },
            close: function( e ) {
                $( this ).find( "p" ).empty();
            }
        }
    });
    
    $(function() {
        
        // Creates the error dialog, using the default options provided
        // above.
        $( ".error-dialog" ).error();
        
        $( ".break-stuff" ).on( "click", function( e ) {
            e.preventDefault();
        
            // Shows the error by using the dialog.open() method,
            // and setting the error content.
            $( ".error-dialog" ).find( "p" ).html( "Got error" )
                                .end()
                                .error( "open" );
                                
        });
        
    });
    
})( jQuery );