jfar jfar - 4 years ago 163
Javascript Question

How to attach to all Jquery.UI.dialog open events to dynamically resize dialog on open?

I'm working with a large existing codebase with tons of legacy code I can't change. My task is to upgrade to the 1.8 version of the UI library. I am having issues with the positioning of a jquery.ui.dialog() element.

The entire site is loaded via javascript ( which I guess is the rage right now ). Tons of HTML gets loaded dynamical which causes positioning issues with the dialog box. Previously the site used custom css position:relative to make sure all of the dialogs were positioned ok.

The dialog's are setup like this:

$('#deletingDialog').dialog({ autoOpen: false, modal: true, position: 'center' });

With UI 1.8 there has been a change in the way dialog() works which breaks this behavior:

Don't change DOM position on open

Dialogs no longer get moved around in
the DOM when they are opened. The only
time the dialog is moved now is during
initialization when it is appended to
the body. This fixes a slew of
problems, such as form elements being
reset, iframes reloading, etc.

All of the dialog() setup code is bound to html elements very early and is in several different places. In a perfect world I'd be able to get in there and change all the dialog calls to be late bound and only setup right before the dialog is supposed to open. This would most likely fix the issue. Unfortunately changing all this code is really prohibitive and defiantly not an option.

What I'm thinking is hooking into the dialog open event http://jqueryui.com/demos/dialog/#event-open and resetting the position right before the modal window actually opens.

So either I can find all the elements with dialogs and then bind via
$( ".selector" ).bind( "dialogopen"
etc etc or hook into the event globally ( preferred ). Either I need a way to say "give me all the elements with a dialog attached" or "always do this code when the open event happens.

Any ideas?

Answer Source

Either I need a way to say "give me all the elements with a dialog attached" or "always do this code when the open event happens.

I think your first idea of using a selector to select all elements that have a dialog widget associated with them. This should be relatively easy--a class ui-dialog-content is applied to each element that the dialog widget is applied to (a wrapper div is inserted around the content). So your code would be:

$(".ui-dialog-content").bind("dialogopen", function() {
    // Reposition dialog, 'this' refers to the element the even occurred on.
    $(this).dialog("option", "position", "top");  

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download