简体   繁体   中英

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?

Try it this way

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

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

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM