Position element but make sure it's still on-screen
<p>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:</p>

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

<p>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.</p>

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