jQuery UI dialog positioning
Asked Answered
R

21

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!

Rosewood answered 13/4, 2009 at 16:50 Comment(1)
As of version 1.9 there is a native tooltip widget.Tensor
D
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.)

Dunk answered 13/4, 2009 at 18:41 Comment(1)
Broken link. I daresay this plugin is no longer maintained. Perhaps it would be wise to select another answer?Subaudition
D
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
    });
}
Daimon answered 14/7, 2010 at 2:40 Comment(5)
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) });Glockenspiel
The jQuery UI position utility doesn't work on hidden elements so you have to open the dialog before positioning it with this code.Chesty
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 itArmelda
I find it confusing that e.g. it has to be: at: 'top+50' instead of at: 'top + 50'Blacklist
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'}, });Darkness
O
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.

Outbreed answered 23/3, 2012 at 13:59 Comment(5)
Works without any additional plugins & intuitive. Best solution I've seen.Historied
Fantastically simple solution, with no additional plugins. This should be the accepted answer.Regime
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.Tl
@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).Sabina
I can't believe that you need so much code just to position a dialog popup.Fewer
S
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]);
});
Staten answered 19/1, 2010 at 19:33 Comment(2)
This answer worked for me, and saved me probably many minutes/hours of googling how to setup the other solutions. Thank you!Deuterogamy
+1 It helped me a lot when I understood .position() gives relative position and .offset(), the absolute position (what I needed)Ahearn
M
17

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");
});
Minaret answered 26/2, 2013 at 11:30 Comment(2)
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.Tickler
i have no clue, is too long ago :DMinaret
A
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.

Abrahamsen answered 23/1, 2015 at 10:14 Comment(4)
This was the exact problem that I had, and this fixed it.Macdonell
My xml transform was failing to add the doctype, this answer along with: https://mcmap.net/q/158746/-set-html5-doctype-with-xslt got things rolling for me.Monocoque
I wish more than 1 upvote for this great answer. It fixed my issue for which i was struggling for hours.Nole
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.Chrisse
T
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.

Troche answered 24/2, 2010 at 15:26 Comment(1)
I think your two variables meant to be myDialogX and myDialogYFelice
D
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.)

Dunk answered 13/4, 2009 at 18:41 Comment(1)
Broken link. I daresay this plugin is no longer maintained. Perhaps it would be wise to select another answer?Subaudition
K
11

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

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

...
    });
Keefe answered 12/6, 2014 at 20:38 Comment(0)
S
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.

Spend answered 23/9, 2011 at 13:15 Comment(0)
E
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});              
         }
    });
Euryale answered 8/4, 2015 at 6:58 Comment(0)
S
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.

Sokol answered 13/4, 2009 at 18:20 Comment(3)
For some reason, document.scrollleft is undefined for me.Rosewood
my bad, its scrollLeft scrollTop forgot to capitalizeSokol
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.Brain
S
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.

Staphylo answered 13/4, 2009 at 19:46 Comment(0)
G
4

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

Guernica answered 10/6, 2010 at 16:30 Comment(0)
N
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]);
}
Newsdealer answered 20/8, 2010 at 14:47 Comment(0)
T
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)
    });
}
Telescope answered 2/8, 2013 at 14:17 Comment(0)
S
3

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

Strontium answered 4/6, 2010 at 8:18 Comment(0)
C
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');

   });
Cratch answered 28/10, 2013 at 16:43 Comment(0)
P
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.

Penniepenniless answered 26/11, 2012 at 12:37 Comment(0)
P
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();

Pelite answered 22/3, 2012 at 2:3 Comment(0)
J
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]
                            });
            })
Jannjanna answered 23/10, 2013 at 21:22 Comment(0)
C
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.

Crenellate answered 8/6, 2017 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.