Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide element when focus lost

I'm working on drop down menu with css and jquery. I wish to be menu open until I click something or until I click out of the menu.

This is what I have tried:

$('#optionButton').click(function() {
$('#dropMenu').css('visibility' , 'visible')    //optionButton clicked, menu visible
});

$('*').not('#optionButton').click(function() {
$('#dropMenu').css('visibility' , 'hidden') //clicked eanithing else: menu close
});

But it doesn't work how I expected.

like image 780
Clem Avatar asked Dec 16 '22 02:12

Clem


2 Answers

When you click on an DOM object, it does event bubbling, which means it starts from the most specific object and bubbles up the DOM tree until it gets to the document object. You can prevent an event from bubbling up the DOM treee by returning false.

$(document).click(function() {
  $('#dropMenu').hide();
});

$('#optionButton').click(function() { 
  $('#dropMenu').show();
  return false;
});

Notice how I used the hide and show methods instead of css('visibility' , 'visible/hidden'). These two actually do slightly different things, nut if you just wanted to hide an element, the hide method is the easiest way to do it in jQuery.

You can see a working example of this on jsFiddle.

like image 151
Peter Olson Avatar answered Dec 27 '22 04:12

Peter Olson


Try this:

$("body").click(function(e) {
    if ( e.target.id === "optionButton" ) {
        $("#dropMenu").css("visibility", "visible");
    }
    else {
        $("#dropMenu").css("visibility", "hidden");
    }
});

Or, the shorter version of the same thing:

$("body").click(function(e) {
    $("#dropMenu").css("visibility", ( e.target.id === "optionButton" ? "visible" : "hidden" ));
});
like image 25
Kevin B Avatar answered Dec 27 '22 02:12

Kevin B