Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript "select box reveal" event or something like it? (using jQuery)

I have an html select:

<select>
    <option>Choose one</option>
</select>

Using jQuery, is there an event I can capture for when the select option list has been revealed? (the reason I need this is because I want to defer population of the list until the moment the list needs to be displayed to the user).

mousedown works for when they click on it, but doesn't do anything if they tab to it and press enter.

focus also works for clicking, and almost works for tabbing to it, but it immediately fires upon tabbing to it rather than waiting until they press enter to reveal the option list. (This is a problem because if they tab to it and then tab on without pressing enter, I don't want the event to fire).

I even came up with this abomination:

var select_reveal = function(ev) { ... }
$('select').on('mousedown', select_reveal).on('keydown', function(ev) {
    // character code 9 is tab
    if (ev.which !== 9) select_reveal.bind(this)(ev);
});

This actually seems to work. It even works for the case where they type an alphabet letter (it populates the list then jumps to the first option starting with that letter). But as I said, this is somewhat of an abomination. It's also a little hacky just checking for "tab" as an exception -- there are definitely other exceptions that won't cause the select to be revealed.

Is there a simple event that covers this use case (or at least something less abominable that covers it)?

(Note: I know there are alternatives to structuring the system like this -- for example, by populating the options ahead of time as they change rather than on the select reveal; but I'm not looking for alternative suggestions, just wondering if there is a solution to the problem explicitly posed).

like image 697
Ben Lee Avatar asked Mar 12 '12 18:03

Ben Lee


1 Answers

I'm not sure which browsers you intend to support but before you get too far down this path please be aware that if you change the content of the select list (e.g. add/change/remove options) that IE will actually swallow the (mouseclick or focus) event that would open the list and leave the user with a closed select list. See here for details: http://webbugtrack.blogspot.com/2009/02/bug-487-onclickonfocus-bugs-on-select.html

I think if you really feel there will be a benefit to delaying the load... I would hide/disable the select list on initial load, and trigger an async load of the options after it has been rendered... re-enabling/showing the select when it is ready.

like image 93
scunliffe Avatar answered Oct 29 '22 04:10

scunliffe