jqueryjquery-uionclicklistenerjquery-eventsjquery-ui-menu

How to hide a jquery ui menu when clicked anywhere else?


I am trying to implement a jquery-ui menu that appears when an object is clicked but disappears when a click is made anywhere other than on the menu itself.

This is the code I have so far:

$("div.item").click(function(e){
        $( "#menu" ).menu( );
        $("#menu").css("top",e.pageY);
        $("#menu").css("left",e.pageX);
        
       });

Now I want to hide and destroy the menu if a click is made anywhere other than on the menu itself.


Solution

  • You want to use the blur event, which fires when an object loses focus. Clicking on something else will take the focus away.

    $("#menu").blur(function () {
        // Your code here to either hide the menu (.toggle())
        // or remove it completely (.remove()).
    });