Hide item when focus is lost

I am working on a drop down menu with css and jquery. I want the menu to be open until I click something or until I exit the menu.

Here is what I 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 this does not work as I expected.

+4
source share
4 answers

Try the following:

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

Or, a shorter version of the same:

 $("body").click(function(e) { $("#dropMenu").css("visibility", ( e.target.id === "optionButton" ? "visible" : "hidden" )); }); 
+3
source

When you click on a DOM object, it fires an event, which means that it starts from the very specific object and bubbles up to the DOM tree until it reaches the document object. You can prevent the DOM tree bubble event 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 want to hide the element, the hide method is the easiest way to do this in jQuery.

You can see a working example of this in jsFiddle .

+4
source

I only experimented with CSS. Maybe this works for you.

Check out http://jsfiddle.net/ZuLHb/1/

+3
source

You can bind a click event to a document to close mΓΉeny:

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

The important role is that you stop distributing the event in the click #optionButton event, otherwise the event will bubble up to the document and execute the click handler attached to it:

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

Demo

+2
source

Source: https://habr.com/ru/post/1401387/


All Articles