Position jQuery UI Dialog Relative to Link or Page Element

Demonstration of positioning a jQuery UI dialog relative to a link or radio buttons. Question from stackoverflow.com. It could be adapted to position under or next to any element on a page. It would work nicely as a form field hint dialog or help dialog.

Two demos are below. One for a single element and one for multiple elements.

Position is adjusted on window resize and scroll.

<div style="text-align:center;"><a id="myLink" href="#">my link</a></div>
<div id="myDialog">
    <p> My positioned dialog</p>
</div>  
$(function() {
    $("#myDialog").dialog({
        autoOpen: false,
        show: 'fade',
        hide: 'fade',
        modal: false,
        width: 200,
        minHeight: 200,
        buttons: {
            "Close": function() {
                $(this).dialog("close");
            }
        }
    });

    $("#myLink").click(function(e) {
        e.preventDefault();
        $("#myDialog").dialog("open");
        return false;
    });

    function positionDialog() {
        linkOffset = $("#myLink").position();
        linkWidth = $("#myLink").width();
        linkHeight = $("#myLink").height();
        scrolltop = $(window).scrollTop();
        $("#myDialog").dialog("option", "position", [(linkOffset.left - 200/2) + linkWidth/2, linkOffset.top + linkHeight - scrolltop]);
    }

    positionDialog();

    $(window).resize(function() {
        positionDialog();
    });

    $(window).scroll(function() {
        positionDialog();
    });
});

Demo for single element on page

Demo for multiple elements on page

Posted in jquery. Tags: , . Permalink. Both comments and trackbacks are closed.

One Comment

  1. Srini
    July 3, 2011 at 7:30 am | Permalink

    Great! However for me, instead of position, offset worked in the line
    linkOffset = $("#myLink").position();