Logo Questions Linux Laravel Mysql Ubuntu Git 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.

like image 839
Ahmed-Anas Avatar asked Dec 14 '12 07:12

Ahmed-Anas


2 Answers

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()).
});
like image 166
Levi Botelho Avatar answered Oct 20 '22 12:10

Levi Botelho


Just to tanks for above code and comment (@death-relic0, @levi-botelho)

// create
$('#menu').blur(function() {
    $('#menu').hide();
});

// show
$('#menu').show().focus();
like image 1
iman Avatar answered Oct 20 '22 13:10

iman