views:

318

answers:

1

I have a jQuery UI dialog that opens when the user clicks a button, and I want the dialog to appear near the button. This is not so hard, for example:

var pos = $('#mybutton').offset();
$('#mydlg').dialog({
    // ...
    autoOpen: false,
    position: [pos.left, pos.top]
});

The problem is when the button is on the far right side of the screen, or at the very bottom of the screen. The newly opened dialog will cause the window to scroll because it goes off screen.

How do I calculate the position so that the dialog opens left/up so it stays on-screen in these cases only?

+1  A: 
    var pos = $('#mybutton').offset();

    //if dialog height/width are known

    var dialogTop = pos.Top;
    var dialogLeft = pos.left;

    if((dialogHeight + pos.top) > $(window).height())
    {
        dialogLeft -= dialogHeight;
    }

    if((dialogWidth + pos.left) > $(window).width())
    {
        dialogLeft -= dialogWidth;
    }

    $('#mydlg').dialog({
        autoOpen: false,
        position: [dialogLeft, dialogTop]
    });

    //if the dialog height/width are unknown then move this to a function in the   dialog onLoad
Shaun Humphries