0

I want to make a simple menu using jQuery UI depending on the position of the cursor. This is EXACTLY what I want: http://medialize.github.io/jQuery-contextMenu/demo/dynamic-create.html but as I said, I want to use jQuery UI. In the example http://jqueryui.com/menu/ the menu is always static on the screen, how can I make it dinamically (shows up near mouse click)?

Thanks in advance,

Lucas.

3
  • Bind a click event, determine when the user right clicks, get the offsets (both x, y), absolutely position your menu container based on those offsets. Show the menu. Voilà! You're done :) Commented Feb 20, 2014 at 19:04
  • yeah ok.. looking at the docs I could find something helpful api.jqueryui.com/position . Imma try it out Commented Feb 20, 2014 at 19:08
  • Cool! If you need help, I'll throw together a quick fiddle later tonight. Commented Feb 20, 2014 at 22:00

1 Answer 1

2

Here's the fiddle that I threw together.

http://jsfiddle.net/uG2EE/

It's not perfect by any means, but it does what you want (uses jQuery UI, shows up near cursor when the context menu event is fired - or right click)

Unfortunately, I had to paste jQuery UI script into the script pane, so you need to scroll to the very bottom. Here's the JS I added to get this working:

$(function() {
    // Set initial state (isVisible) then initialize menu
    $("#menu").data('isVisible', false).menu();

    // Initialize event handlers
    $(document).on({
        // Click is responsible for closing the menu, when it is visible
        'click': function(e){
            if(e.which === 1 && $('#menu').data('isVisible')){
                $("#menu").css({
                'display' : 'none'
                }).data('isVisible', false);
            }
        },
        // "onContextMenu" event is fired when user right clicks. We prevent the
        // default by calling e.preventDefault(), and then display our jQuery-UI menu
        'contextmenu': function(e){
            var x = e.clientX,
                y = e.clientY;

            e.preventDefault();

            // Check state (isVisible) to see if menu needs to be displayed
            if($('#menu').data('isVisible') === false) {
                $("#menu").css({
                'display' : 'block',
                'left' : x + 10,
                'top' : y + 10
                }).data('isVisible', true);
            }
        }
    });
});

The CSS is very straight forward: display:none, position:absolute, and the width.

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.