How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?

This used to actually be possible with HTML+Javascript, despite everywhere else people say it is not, but it was deprecated later on and does not work now.

However, this only worked in Chrome. Read more if you’re interested.


According to W3C Working Draft for HTML5, Section 3.2.5.1.7. Interactive Content:

Certain elements in HTML have an activation behavior, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism […] for instance using keyboard or voice input, or through mouse clicks.

When the user triggers an element with a defined activation behavior in a manner other than clicking it, the default action of the interaction event must be to run synthetic click activation steps on the element.

<select> being an Interactive Content, I believed that it is possible to programatically display its <option>s. After a few hours of playing around, I discovered that using document.createEvent() and .dispatchEvent() works.

That said, demo time. Here is a working Fiddle.


HTML:

<select id="dropdown">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
</select>
<br>
<button id="fire" type="button" onclick="runThis()">Show dropdown items</button>​

Javascript:

// <select> element displays its options on mousedown, not click.
showDropdown = function (element) {
    var event;
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    element.dispatchEvent(event);
};

// This isn't magic.
window.runThis = function () { 
    var dropdown = document.getElementById('dropdown');
    showDropdown(dropdown);
};

If anyone finds a way to do the same but not in Chrome, please feel free to modify this fiddle.

Leave a Comment