Retaining Scroll Position With Dialogs

When a dialog widget loses focus, scrollable content loses it's scroll position. You have to explicitly store it.

by Adam Boduch

HTML

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<div class="dialog" title="First">
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
</div>

<div class="dialog" title="Second">
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
    <p>Content...</p>
</div>

CSS

body {
    font-size: 0.8em;
}

JavaScript

$(function() {

    // Create dialogs with fixed height.
    var $dialogs = $( ".dialog" ).dialog( { height: 200 } );
    
    // Position the dialogs.
    $dialogs.first().dialog( "option", "position", {
        my: "left",
        at: "left",
        of: window
    }).end().last().dialog( "option", "position", {
        my: "right",
        at: "right",
        of: window
    });
    
    $dialogs.on({
        // Stores the scroll position of the scrolled element.
        scroll: function( e ) {
            $( this ).data( "st", $( this ).scrollTop() );
        },
        // Reset the scoll positions of "unfocused" dialog elements
        // that have the "st" data.
        dialogfocus: function( e, ui ) {
            $( ":ui-dialog" ).not( this ).each(function() {
                var st = $( this ).data( "st" );
                if ( typeof st !== "undefined" ) {
                    $( this ).scrollTop( st );
                }
            });
        }
    });
    
});