Opening JQuery Ui Dialog in MousePosition
Asked Answered
K

3

12

i want to open JQuery UI Dialog In Mouse Position. what is the problem with my code?

<script type="text/javascript">

    $(document).ready(function () {
        var x;
        var y;
        $(document).mousemove(function (e) {
            x = e.pageX;
            y = e.pageY;
        });

        $("#d").dialog({
            autoOpen: false,
            show: "blind",
            hide: "explode",
            position: [x, y]
        });
        $("#c").bind("mouseover", function () {
            $("#d").dialog('open'); // open
        });


        $("#c").bind("mouseleave", function () {
            $("#d").dialog('close'); // open
        });



    });



</script>
Kirkuk answered 29/12, 2010 at 8:16 Comment(0)
L
16

Updating x and y after they're passed (by value) to setup the dialog won't have any effect, since the variables aren't related after that. You'll need to update the position option directly, like this:

$(document).mousemove(function (e) {
    $("#d").dialog("option", { position: [e.pageX, e.pageY] });
});

You can test it out here, or the much more optimized version (since you only show it on top of #c anyway):

$(function () {
    $("#d").dialog({
        autoOpen: false,
        show: "blind",
        hide: "explode"
    });
    $("#c").hover(function () {
        $("#d").dialog('open');
    }, function () {
        $("#d").dialog('close');
    }).mousemove(function (e) {
        $("#d").dialog("option", { position: [e.pageX+5, e.pageY+5] });
    });
});

You can test that version here.

Lucillalucille answered 29/12, 2010 at 8:19 Comment(1)
not working. it is not close to mouspointer, somewhere in middle of screenLoader
J
10

The answer of Nick Craver works, only need an improvement, in order to the box be always near the cursor.

The Y-axis needs to be subtracted by the scrollTop of the page. So that line becomes:

$("#d").dialog("option", { position: [e.pageX+5, (e.pageY+5)-$(document).scrollTop()] });
Jollification answered 21/2, 2012 at 18:9 Comment(0)
B
5
$("#d").dialog(
    "option", 
    {
        position: 
        {
            my: 'left', 
            at: 'right', 
            of: event
        }
    }
);

Working sample: http://jsbin.com/okosi4

This solution worked better for me when I had a long page that required scrolling. I found the above solutions didn't work well with vertical scrolling.

See more about position option

Bela answered 29/7, 2013 at 20:34 Comment(2)
I followed the "Working sample" link, but it says the "free preview time has expired"Michaeu
so... copy paste the content to a fiddle or similar.Rexford

© 2022 - 2024 — McMap. All rights reserved.