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?
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.
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.
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.
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().
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
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()
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With