Friday, November 1, 2013

Position Dialog Based On Click Events

With the jQuery UI dialog component, you can specify where you would like it positioned, when opened. For example, in the call to create the dialog instance, you might pass the position option. By default, the dialog opens automatically, and so if you need the default position changed, you have to specify the custom position when the widget is first instantiated.
$( "#dialog" ).dialog({
    position: {
        my: "top",
        at: "top",
        of: window
    }
});

This code will position the dialog at the top of the window, and open it immediately. This is because we haven't set the autoOpen option to false, a common practice. Usually we're opening a dialog in response to some user action — a click event for example. Well, the trick to that is — we don't know in advance where to position the dialog. The safest bet is to keep the default position — right in the middle of the window. But in some cases, closer proximity to the click event makes sense.

Here is an example approach to doing just that.

$( ".opener" ).on( "click", function( e ) {
    var pos = [ e.pageX, e.pageY ];
    $( "#dialog" ).dialog( "option", "position", pos )
                  .dialog( "open" );    
});

With every click on .opener, we're resetting the dialog position to match that of the event coordinates. This gets passed right to the position option since it accepts an array of XY coordinates.

No comments :

Post a Comment