118

I am trying to use the jQuery dialog UI library in order to position a dialog next to some text when it is hovered over. The jQuery dialog takes a position parameter which is measured from the top left corner of the current viewport (in other words, [0, 0] will always put it in the upper left hand corner of your browser window, regardless of where you are currently scrolled to). However, the only way I know to retrieve the location is of the element relative to the ENTIRE page.

The following is what I have currently. position.top is calculated to be something like 1200 or so, which puts the dialog well below the rest of the content on the page.

$(".mytext").mouseover(function() {
    position = $(this).position();
    $("#dialog").dialog('option', 'position', [position.top, position.left]);
}

How can I find the correct position?

Thanks!

Wickethewok
  • 6,534
  • 11
  • 42
  • 40

21 Answers21

111

As an alternative, you could use the jQuery UI Position utility e.g.

$(".mytext").mouseover(function() {
    var target = $(this);
    $("#dialog").dialog("widget").position({
       my: 'left',
       at: 'right',
       of: target
    });
}
Brian M. Hunt
  • 81,008
  • 74
  • 230
  • 343
  • 30
    This is the best approach. I will note though, that if you're creating the dialog for the first time, you'll need an extra call to `dialog` like this: `$('#dialog').dialog({ width: 300 /* insert your options */ }).dialog('widget').position({ my: 'left', at: 'right', of: $(this) });` – wsanville Dec 16 '10 at 16:13
  • 27
    The jQuery UI position utility doesn't work on hidden elements so you have to open the dialog before positioning it with this code. – Toadmyster Dec 15 '11 at 22:46
  • 1
    jQuery UI is the best way to do it. [Scott González](http://tech.pro/tutorial/1262/simplifying-dynamic-positioning-with-jquery-ui) has an in-depth explanation of how jQuery UI works and how to use it – strangeloops May 09 '13 at 06:01
  • I find it confusing that e.g. it has to be: `at: 'top+50'` instead of `at: 'top + 50'` – Yasen Jan 02 '18 at 08:53
  • 3
    for anyone struggling (as i just was) with how to set more than one position it's like this: `$('dialog').dialog({ position: { my: 'left top', at: 'left+50 top+50'}, });` – milpool Oct 27 '19 at 20:40
85

Thanks to some answers above, I experimented and ultimately found that all you need to do is edit the "position" attribute in the Modal Dialog's definition:

position:['middle',20],

JQuery had no problems with the "middle" text for the horizontal "X" value and my dialog popped up in the middle, 20px down from the top.

I heart JQuery.

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
user1288395
  • 967
  • 6
  • 4
  • Works without any additional plugins & intuitive. Best solution I've seen. – PlanetUnknown Aug 31 '13 at 15:58
  • Fantastically simple solution, with no additional plugins. This should be the accepted answer. – kamui Sep 26 '13 at 14:48
  • 15
    Darn, that's nice but it's deprecated- "Note: The String and Array forms are deprecated." http://api.jqueryui.com/dialog/#option-position So you'd need to use the position object my/at/of thingy. See the link there about "jQuery UI Position". You could get something like position: { my: "center top", at: "center top+20", of: window } to work like you want. See link for more examples. – Michael K Nov 12 '13 at 20:50
  • 1
    @mikato ... according to [jquery ui 1.10](http://api.jqueryui.com/dialog/#option-position), position does accept the string and array. ... ... but I still like the object notation (I like the keys). – dsdsdsdsd Dec 11 '13 at 15:37
  • 3
    I can't believe that you need so much code just to position a dialog popup. – Gi1ber7 May 08 '17 at 15:01
42

After reading all replies, this finally worked for me:

$(".mytext").mouseover(function() {
    var x = jQuery(this).position().left + jQuery(this).outerWidth();
    var y = jQuery(this).position().top - jQuery(document).scrollTop();
    jQuery("#dialog").dialog('option', 'position', [x,y]);
});
sth
  • 222,467
  • 53
  • 283
  • 367
Jaymin Patel
  • 421
  • 4
  • 2
  • This answer worked for me, and saved me probably many minutes/hours of googling how to setup the other solutions. Thank you! – Nathan Feb 28 '12 at 13:44
  • 1
    +1 It helped me a lot when I understood .position() gives relative position and .offset(), the absolute position (what I needed) – daniloquio Mar 09 '12 at 19:43
17

Check your <!DOCTYPE html>

I've noticed that if you miss out the <!DOCTYPE html> from the top of your HTML file, the dialog is shown centred within the document content not within the window, even if you specify position: { my: 'center', at: 'center', of: window}

EG: http://jsfiddle.net/npbx4561/ - Copy the content from the run window and remove the DocType. Save as HTML and run to see the problem.

Daniel Flippance
  • 7,734
  • 5
  • 42
  • 55
  • 3
    This was the exact problem that I had, and this fixed it. – BobRodes May 26 '16 at 19:56
  • 1
    My xml transform was failing to add the doctype, this answer along with: http://stackoverflow.com/questions/3387127/set-html5-doctype-with-xslt got things rolling for me. – Daniel Bower Apr 19 '17 at 19:42
  • 2
    I wish more than 1 upvote for this great answer. It fixed my issue for which i was struggling for hours. – Dr. DS Mar 05 '19 at 06:11
  • 1
    An error string printed on top of my php script, that is why cause this issue. You got my point what I needed to check at first. – Abbas Apr 27 '21 at 08:50
16

http://docs.jquery.com/UI/API/1.8/Dialog

Example for fixed dialog on the left top corner:

$("#dialogId").dialog({
    autoOpen: false,
    modal: false,
    draggable: false,
    height: "auto",
    width: "auto",
    resizable: false,
    position: [0,28],
    create: function (event) { $(event.target).parent().css('position', 'fixed');},
    open: function() {
        //$('#object').load...
    }
});

$("#dialogOpener").click(function() {
    $("#dialogId").dialog("open");
});
xhochn
  • 160
  • 1
  • 4
  • for me this was the simplest to follow, just an attribute and you get the solution. i didnt know that "position" could be mentioned with this square brackets syntax along with height/width etc up there. – user734028 Oct 29 '19 at 08:40
  • i have no clue, is too long ago :D – xhochn Oct 30 '19 at 10:28
16

Taking Jaymin's example a step further, I came up with this for positioning a jQuery ui-dialog element above the element you've just clicked (think "speech bubble"):

$('#myDialog').dialog( 'open' );
var myDialogX = $(this).position().left - $(this).outerWidth();
var myDialogY = $(this).position().top - ( $(document).scrollTop() + $('.ui-dialog').outerHeight() );
$('#myDialog').dialog( 'option', 'position', [myDialogX, myDialogY] );

Note that I "open" the ui-dialog element before calculating the relative width and height offsets. This is because jQuery can't evaluate outerWidth() or outerHeight() without the ui-dialog element physically appearing in the page.

Just be sure to set 'modal' to false in your dialog options and you should be a-OK.

markedup
  • 1,247
  • 2
  • 12
  • 21
12

Check out some of the jQuery plugins for other implementations of a dialog. Cluetip appears to be a feature-rich tooltip/dialog style plug-in. The 4th demo sounds similar to what you are trying to do (although I see that it doesn't have the precise positioning option that you're looking for.)

John
  • 1,210
  • 5
  • 23
  • 51
Ben Koehler
  • 8,633
  • 3
  • 23
  • 23
  • Broken link. I daresay this plugin is no longer maintained. Perhaps it would be wise to select another answer? – JohnK Jun 29 '20 at 15:46
11

To put it right on top of control, you can use this code:

    $("#dialog-edit").dialog({
...    
        position: { 
            my: 'top',
            at: 'top',
            of: $('#myControl')
        },

...
    });
live-love
  • 48,840
  • 22
  • 240
  • 204
7
$("#myid").dialog({height:"auto",
        width:"auto",
        show: {effect: 'fade', speed: 1000},
        hide: {effect: 'fade', speed: 1000},
        open: function( event, ui ) {
          $("#myid").closest("div[role='dialog']").css({top:100,left:100});              
         }
    });
Günes Erdemi
  • 71
  • 1
  • 2
7
$(".mytext").mouseover(function() {
   var width = 250;
   var height = 270;
   var posX = $(this).offset().left - $(document).scrollLeft() - width + $(this).outerWidth();
   var posY = $(this).offset().top - $(document).scrollTop() + $(this).outerHeight();
   $("#dialog").dialog({width:width, height:height ,position:[posX, posY]});
}

Positions a dialog just under an element. I used offset() function just because it calculates the position relative to upper left corner of the browser, but position() function calculates the position relative to parent div or iframe that parent of the element.

M. Belen
  • 71
  • 1
  • 1
6

instead of doing pure jquery, i would do:

$(".mytext").mouseover(function() {
    x= $(this).position().left - document.scrollLeft
    y= $(this).position().top - document.scrollTop
    $("#dialog").dialog('option', 'position', [y, x]);
}

if i am understanding your question correctly, the code you have is positioning the dialog as if the page had no scroll, but you want it to take the scroll into account. my code should do that.

Dylan Beattie
  • 53,688
  • 35
  • 128
  • 197
Samuel
  • 16,923
  • 6
  • 62
  • 75
  • For some reason, document.scrollleft is undefined for me. – Wickethewok Apr 13 '09 at 19:25
  • 2
    my bad, its scrollLeft scrollTop forgot to capitalize – Samuel Apr 13 '09 at 21:50
  • var x = el.position().left + el.outerWidth(); var y = el.position().top - $(document).scrollTop(); worked for me. Problem is I can't get the height and width of the dialog after I change the info in it. – rball Oct 19 '09 at 18:09
4

To fix center position, I use:

open : function() {
    var t = $(this).parent(), w = window;
    t.offset({
        top: (w.height() / 2) - (t.height() / 2),
        left: (w.width() / 2) - (t.width() / 2)
    });
}
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
4

a bit late but you can do this now by using $j(object).offset().left and .top accordingly.

user363690
  • 41
  • 1
4

I don't think the speech bubble is quite right. I tweaked it a bit so that it would work and the item opens right under the link.

function PositionDialog(link) {
    $('#myDialog').dialog('open');
    var myDialogX = $(link).position().left;
    var myDialogY = $(link).position().top + $(link).outerHeight();
    $('#myDialog').dialog('option', 'position', [myDialogX, myDialogY]);
}
cliff
  • 41
  • 1
4

This page shows how to determine your scroll offset. jQuery may have similar functionality but I couldn't find it. Using the getScrollXY function shown on the page, you should be able to subtract the x and y coords from the .position() results.

Philip Tinney
  • 1,986
  • 17
  • 19
3

Here is the code..,how to position the jQuery UI dialog to center......

var $about = $("#about");

   $("#about_button").click(function() {
      $about.dialog({
         modal: true,
         title: "About the calendar",
         width: 600,         
         close: function() {
            $about.dialog("destroy");
            $about.hide();
         },
         buttons: {
            close : function() {
               $about.dialog("close");
            }
         }
      }).show();

      $about.dialog("option", "position", 'center');

   });
Manu R S
  • 872
  • 9
  • 6
3

you can use $(this).offset(), position is related to the parent

EdChum
  • 376,765
  • 198
  • 813
  • 562
neil tang
  • 31
  • 1
2

I've tried all the proposed solutions but they won't work because the dialog is not part of the main document and will has its own layer (but thats my educated guess).

  1. Initialize the dialog with $("#dialog").dialog("option", "position", 'top')
  2. Open it with $(dialog).dialog("open");
  3. Then get the x and y of the displayed dialog (not any other node of the document!)

    var xcoord = $(dialog).position().left + ADD_MODIFIER_FOR_X_HERE;

    var ycoord= $(dialog).position().top + ADD_MODIFIER_FOR_Y_HERE;

    $(dialog).dialog('option', 'position', [xcoord , ycoord]);

This way the coordinates are from the dialog not from the document and the position is altered according to the layer of the dialog.

Mr.Mountain
  • 863
  • 8
  • 32
1

above solutions are very true...but the UI dialog does not retain the position after window is resized. below code does this

            $(document).ready(function(){

                $(".test").click(function(){
                            var posX = $(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
                            var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();
                            console.log("in click function");
                            $(".abc").dialog({
                                position:[posX,posY]
                            });

                        })

            })

            $(window).resize(function(){
                var posX=$(".test").offset().left - $(document).scrollLeft() + $(".test").outerWidth();
                var posY = $(".test").offset().top - $(document).scrollTop() + $(".test").outerHeight();

            $(".abc").dialog({
                                position:[posX,posY]
                            });
            })
Kaustubh - KAY
  • 119
  • 1
  • 3
1

I tried for many ways to get my dialog be centered on the page and saw that the code:

$("#dialog").dialog("option", "position", 'top')

never change the dialog position when this was created.

Instead of, I change the selector level to get the entire dialog.

$("#dialog").parent() <-- This is the parent object that the dialog() function create on the DOM, this is because the selector $("#dialog") does not apply the attributes, top, left.

To center my dialog, I use the jQuery-Client-Centering-Plugin

$("#dialog").parent().centerInClient();

jmozko
  • 371
  • 3
  • 6
0

You ca set top position in style for display on center, saw that the code:

.ui-dialog{top: 100px !important;}

This style should show dialog box 100px bellow from top.