Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a universal way to "close" a <select> dropdown menu (not .blur() )?

There's a neat trick you can use to "close" a <select> dropdown menu.

$('#test').click(function(){
    $('#test').hide();
    setTimeout(function(){
        $('#test').show();
    },20);
});​

This seems to always work for Chrome and Firefox on Windows. IE works in my actual code, but when I test the jsfiddle code in IE, it doesn't work. And on a mac, this doesn't work for any browser. The difference between Mac and Windows is that on Mac, the options are opened in their own element (kinda - inspecting the page shows no new elements). So the dropdown bar hides and comes back, but the new menu with the options aren't considered a part of $('#test') so they don't hide. In Windows, the menu with options is considered part of $('#test') so when you hide that, the menu hides along with it.

So the question is, is there a way to "close" a <select> dropdown menu that works in any browser and on any OS?


UPDATE

I don't mean using .blur() and this is why. I have some code that emulates a dropdown menu but is actually <select multiple>. So I have just a normal <select> visible and when I click on it, I replace it with an absolutely positioned <select multiple> element. After selecting the options, this goes away and the <select> element comes back. Any help on this would be great.

like image 565
Aust Avatar asked Oct 15 '12 18:10

Aust


People also ask

How do I close a select drop down?

The escape key can often be used to get you out of dialogs or dropdown lists - it generally represents the pressing of the cancel button in these cases.

How do you make a dropdown Close by clicking outside?

Answer: Use the jQuery on() method You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.

How do I stop dropdown menu Close menu items on clicking inside?

As all Twitter Bootstrap users know, the dropdown menu closes on click (even clicking inside it). To avoid this, I can easily attach a click event handler on the dropdown menu and simply add the famous event. stopPropagation().


2 Answers

I haven't tested it yet but I would imagine, you can just

$('select').blur();

or set focus on something else to close it

Update - oh there you go first commenter has the fiddle

like image 56
Huangism Avatar answered Sep 28 '22 17:09

Huangism


If you change the event from click to focus, it might help:

$("#test").focus(function () {
    // Your original code

    // or: this.blur();
    // just DON'T call this.focus()
});
like image 30
Ian Avatar answered Sep 28 '22 17:09

Ian