Skip to content

Dropdown

Defined in: components/dropdown/dropdown.ts:72

Converts select menus into menus made of divs, so that they can be styled.

  • Every <select> on the page is converted, except those with the class system.
  • The <select> stays in the page, hidden off screen and marked with the class js-styled, so forms still submit it. The custom select is added right after it.
  • When a different option is chosen, a real change event is fired on the <select>. It bubbles, so select.addEventListener('change', ...) and a listener on the form both hear it. The focus and blur of the <select> are the browser’s own: they fire when it is reached with the keyboard.
  • optgroup and multiple selection are not supported.
  • Not accessible: there is no keyboard support.
  • The script build converts the page for you when it loads, and ML.Dropdown() converts the <select>s that were added later. With modules, create one Dropdown and call Dropdown.init.

Markup

<select id="fruits" name="fruits">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="strawberry">Strawberry</option>
</select>

Converting selects that were added later

dropdown.init();

The markup it creates

<div class="dropdown" data-value="apple" style="width: 114px;">
<a href="#" class="dropdown-link" tabindex="-1" data-index="0">Apple</a>
<ul class="dropdown-menu">
<li data-value="apple" data-index="0"><a href="#" tabindex="-1">Apple</a></li>
<li data-value="orange" data-index="1"><a href="#" tabindex="-1">Orange</a></li>
<li data-value="strawberry" data-index="2"><a href="#" tabindex="-1">Strawberry</a></li>
</ul>
</div>

new Dropdown(): Dropdown

Dropdown

destroy(): void

Defined in: components/dropdown/dropdown.ts:106

Removes the custom selects and every listener, and gives the <select>s back. The <select>s can be converted again with Dropdown.init.

void


init(): void

Defined in: components/dropdown/dropdown.ts:83

Converts the <select>s that are not converted yet. Call it again after adding <select>s to the page: the ones that are already converted are left alone.

If the page is still loading, it waits until the DOM is ready.

void