119

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!

1
  • 2
    As of version 1.9 there is a native tooltip widget.
    – theblang
    Commented Apr 25, 2013 at 14:09

21 Answers 21

112

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
    });
}
5
  • 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
    Commented Dec 16, 2010 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
    Commented Dec 15, 2011 at 22:46
  • 1
    jQuery UI is the best way to do it. Scott González has an in-depth explanation of how jQuery UI works and how to use it Commented May 9, 2013 at 6:01
  • I find it confusing that e.g. it has to be: at: 'top+50' instead of at: 'top + 50'
    – Yasen
    Commented Jan 2, 2018 at 8:53
  • 4
    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
    Commented Oct 27, 2019 at 20:40
86

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.

5
  • Works without any additional plugins & intuitive. Best solution I've seen. Commented Aug 31, 2013 at 15:58
  • Fantastically simple solution, with no additional plugins. This should be the accepted answer.
    – kamui
    Commented Sep 26, 2013 at 14:48
  • 15
    Darn, that's nice but it's deprecated- "Note: The String and Array forms are deprecated." 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
    Commented Nov 12, 2013 at 20:50
  • 1
    @mikato ... according to jquery ui 1.10, position does accept the string and array. ... ... but I still like the object notation (I like the keys).
    – dsdsdsdsd
    Commented Dec 11, 2013 at 15:37
  • 3
    I can't believe that you need so much code just to position a dialog popup.
    – Gi1ber7
    Commented May 8, 2017 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]);
});
2
  • This answer worked for me, and saved me probably many minutes/hours of googling how to setup the other solutions. Thank you!
    – Nathan
    Commented Feb 28, 2012 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
    Commented Mar 9, 2012 at 19:43
18

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");
});
2
  • 1
    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
    Commented Oct 29, 2019 at 8:40
  • i have no clue, is too long ago :D
    – xhochn
    Commented Oct 30, 2019 at 10:28
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.

4
  • 3
    This was the exact problem that I had, and this fixed it.
    – BobRodes
    Commented May 26, 2016 at 19:56
  • 1
    My xml transform was failing to add the doctype, this answer along with: stackoverflow.com/questions/3387127/set-html5-doctype-with-xslt got things rolling for me. Commented Apr 19, 2017 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
    Commented Mar 5, 2019 at 6: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
    Commented Apr 27, 2021 at 8:50
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.

1
  • 1
    I think your two variables meant to be myDialogX and myDialogY
    – casey
    Commented Oct 14, 2010 at 16:39
11

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.)

1
  • Broken link. I daresay this plugin is no longer maintained. Perhaps it would be wise to select another answer?
    – JohnK
    Commented Jun 29, 2020 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')
        },

...
    });
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.

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});              
         }
    });
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.

3
  • For some reason, document.scrollleft is undefined for me. Commented Apr 13, 2009 at 19:25
  • 2
    my bad, its scrollLeft scrollTop forgot to capitalize
    – Samuel
    Commented Apr 13, 2009 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
    Commented Oct 19, 2009 at 18:09
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.

4

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

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]);
}
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)
    });
}
3

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

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');

   });
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.

0
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();

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]
                            });
            })
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.