Thursday, July 3, 2014

jQuery UI: Maximizing Dialogs

The dialog widget can be resized by the user, as well as programatically, using the API. Dialogs can also be dragged around on the screen if the draggable option is left on — the default. Sometimes, just like a real desktop window, you may want to maximize the dialog to occupy the full browser window. Blot out all the other distractions, so to speak.

Here's a demonstration that will resize the dialog widget if it's dragged to the top left corner of the browser window.

$( '#dialog' ).dialog({
    
    dragStart: function( e, ui ) {
        
        var $this = $( this ),
            width = $this.data( 'prevWidth' ),
            height = $this.data( 'prevHeight' );
        
        if ( width && height ) {
            $this.removeData( 'prevWidth prevHeight' )
                .dialog( 'option', {
                    width: width,
                    height: height
                });
        }

    },
    
    dragStop: function( e, ui ) {
        
        var top = ui.position.top,
            left = ui.position.left,
            $this = $( this );
        
        if ( top !== 0 && left !== 0 ) {
            return
        }
        
        $this.data({
            prevWidth: $this.dialog( 'option', 'width' ),
            prevHeight: $this.dialog( 'option', 'height' )
        }).dialog( 'option', {
            width: $( 'body' ).width() - 4,
            height: $( document ).height() - 4
        });
        
    }
    
});

The two events we're interested in are dragStart, and dragStop. When dragging starts, we need to check for prevWidth and prevHeight data. If they're there, it means that the dialog has already been maximized, and now we need to restore it to it's previous size dimensions.

In the dragStop event handler, we only respond if the position of the dialog has reached the top left corner of the window. At which point, we store the original width and height of the dialog, and resize it to the browser window dimensions.

No comments :

Post a Comment