Search code examples
javascriptjquerycontextmenu

Positioning Context Menu


I'm trying to position a custom context menu with jQuery.
The first time it appears at the right position (mouse coordinates), but then the current position is being summed up with the new position, so that the menu disappears from the screen.
Here is the JavaScript:

<script>
$(function(){
    $('#box').hide();

    $(document).bind("contextmenu", function(e) {
        $("#box").offset({left:e.pageX, top:e.pageY});
        $('#box').show();
        e.preventDefault();
    });

    $(document).bind("click", function(e) {
        $('#box').hide();
    });
    $('#box').bind("click", function(e) {
        $('#box').hide();
    });
});
</script>

Solution

  • Don't use offset method, try css instead, positioning context menu absolutely:

    $("#box").css({left:e.pageX, top:e.pageY});
    

    CSS:

    #box {
        ...
        position: absolute;
    }
    

    http://jsfiddle.net/smxLk/