Opening JQuery Ui Dialog in MousePosition

Shahin picture Shahin · Dec 29, 2010 · Viewed 25.3k times · Source

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>

Answer

Nick Craver picture Nick Craver · Dec 29, 2010

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.