Reputation: 11602
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.
Upvotes: 7
Views: 13420
Reputation: 50905
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()
});
Upvotes: 1
Reputation: 29005
select
is not meant for this, you can however create some other markup to fake
the select
layout.
HTML
JS
$('#test').click(function() {
$(this).toggleClass('open');
}).find('li').not(':first').on('hover',function() {
$(this).parent().removeClass('open');
});
CSS
ul {
list-style:none ;
border : solid 1px Gray;
width: 80px;
height: 20px;
overflow:hidden;
cursor:pointer;
}
ul.open {
height: 60px;
}
Here's a demo. You can style the markup as you want.
Upvotes: 1
Reputation: 79830
How about using .blur()
on click()
.. unfortunately I cannot test them all now..
$('select').click(function(){
$(this).blur();
});
DEMO: http://jsfiddle.net/vqA3M/7/
Upvotes: 0
Reputation: 16438
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
Upvotes: 3