Saturday, February 13, 2021

A dropdown menu for toolbars using standard HTML elements

I wanted a dropdown menu in HTML but without the tons of javascript and complex stylesheets usually associated with such designs. My dropdown menu is built from two standard HTML elements: an input of type button, and a select. It needs a little vanilla javascript and css to make it work, but it is not excessive. It works on all major browsers.

Why not just use an ordinary select element on its own? Because then the currently selected item would occupy a variable amount of horizontal space. This menu is intended for use in a toolbar where space is at a premium. This way the button driving the menu is always only 1-character or 1 icon wide. With a variable width select if you choose a long item then the other buttons may wrap around onto the next line. Of course in select you can set its width to be a fixed value but then the current value is often unreadable.

Here's the code:

The basic idea is to have a button on one line and a select on the next, separated by a <br>. The select menu is initially invisible. Clicking on the button makes it visible. Then it works like a normal select element, except that if you change the selected option or select the same one it makes the menu disappear. Enclosing the menu and its button in a div that is absolutely positioned makes the menu float over subsequent text, rather than pushing it down.

Here's the thing in action. (The label for the current value is for demo purposes, and in practice should be omitted or placed elsewhere on the page.)


And some more text here.