Login Register

Position Dialog relative to a node

How do i create a Dialog box and position it relative to an existing element/node?
I want to do it in the code (shown below), as against using tags. In the sample code below, i would like to open the Dialog right below the link to "New".
I am only able to get the dialog box come up in the dead center of the page.
Thanks.

Version: Dojo 1.0
Usage:

function addNew() {
    dijit.byId('addDlg').show();
}

<a href="javascript:addNew();">New</a> <!-- link to bring up Dialog box -->

<div dojoType="dijit.Dialog" id="addDlg" title="Add" execute="alert('Submitted');">
    <table>
      .... form elements here ....
    </table>
</div>

The Dialog is designed to be

The Dialog is designed to be displayed in the center of the viewport.

The easiest way to reposition it, but maybe not what you would like, is to show it (will open in the center), then position it where you want it.

I believe the Dialog's parentNode will be the document.body, so positioning will be relative to that.

For example, after "show", do this:

dijit.byId('myDialog').domNode.style.left='200px';
dijit.byId('myDialog').domNode.style.top='200px';

would move the Dialog to that location, after initial display.

To determine where to move it, you can do your math against the current position of the element you want the Dialog to be positioned near.

To get that element's current position, you can use dojo.coords(thatElement). dojo.coords of an html element returns the position as pixels left, top, width, height, abs x, abs y, e.g.,

position = dojo.coords(dijit.byId('myWidget').domNode);
leftPixels = position.l;
absXpixels = position.x;

etc.

note that your method, while

note that your method, while affective, will jump back to the center of the scroll if the window scrolls or resizes (possibly) ... A better solution would be to use a ToolTipDialog around the node, or use a floating pane and position it absolutely. (though the modal option is no longer available)

Repositioning works as suggested

Repositioning, as suggested by frankf works. There seems to be no issue with the Dialog jumping back on window realign.

Thanks for your help!

working code sample

function addNew() {
    position = dojo.coords(dojo.byId(hrefId));       
    dijit.byId('addDlg').show();                                       
    dijit.byId('addDlg').domNode.style.left = (position.x + 'px');
    dijit.byId('addDlg').domNode.style.top  = (position.y + 'px');     
}

great. you can eliminate

great.

you can eliminate some overhead in the above function like this:

function addNew(){
    var pos = dojo.coords(dojo.byId(hrefid));
    var mine = dijit.byId('addDlg');
    mine.show();
    mine.domNode.style.left = (pos.x)+"px";
    mine.domNode.style.top = (pos.y)+"px"; 
}

(eg: only call dijit.byId once) ... just a note.