Patrik
Patrik

Reputation: 2247

Click event when not clicking on an element

Maybe I'm, just tired but I have a right click menu that I want to close when the user clicks anywhere else than the menu. But I cant figure out how to make it disappear when the user clicks on something else.

Here is the code for showing the menu:

// If mouse click on was pressed
$('#content_list table tr').bind('mouseup', function(event) {
    // if right click
    if(event.which == 3) {
        showRightClickMenu(event);
    }
    event.preventDefault();
    event.stopPropagation();
});

And this is what I got for hiding the menu

// If mouse click outside document
$(document).bind('blur', function(event) {
    hideRightClickMenu();
    event.stopPropagation();
});

// If mouse click not on the menu
$('*:not(#rightClickMenu *)').bind('mousedown keydown', function(event) {
    hideRightClickMenu();
    event.stopPropagation();
});

The first bind checks if the user clicks outside the document and the second bind checks if the user clicks on everything except the menu. But the second one doesn't really work. If I click on the menu the menu is hidden.

Shouldn't be so hard imo... Anyone got any ideas?

Upvotes: 1

Views: 172

Answers (2)

elclanrs
elclanrs

Reputation: 94121

Try with focusout() event and using on() instead of old bind(). This will work even with multiple submenus. http://jsfiddle.net/elclanrs/jhaF3/1/

// Something like this...
$('#menu li').on('click', function() {
    $(this).find('ul').show();
}).find('ul').on('focusout', function(){
    $(this).hide();
});

Upvotes: 0

Cheery
Cheery

Reputation: 16214

Try it this way

$(document.body).bind('click', function() {
    hideRightClickMenu();
});

$(window).bind('blur', function() {
    hideRightClickMenu();
});

Upvotes: 1

Related Questions