DEV Community

Cover image for Modern Dropdown component HTML
Amjad Abujamous
Amjad Abujamous

Posted on • Updated on

Modern Dropdown component HTML

TL;DR

I wanted to challenge myself to build a custom dropdown component that works with HTML forms and looks the same on all platforms and browsers. I finally managed to make one, and here is how...

Code

The code can be found on this Code Pen.

How it's done

  • Create a native web component that extends HTML Element.
  • Give it the ability to have multiple themes (using pre-defined colors in CSS).
  • Allow to set its items either using setAttribute or by firing an event which has the items in it.
  • Listen to a custom event indicating when an item is selected.
  • Give it the ability to be a part of any HTML form. Note that element-internals-polyfill is needed for this to work on some browsers such as Safari at the time of writing this article.

UI of the dropdown component

It is composed of three elements.

  1. a read-only input element which displays the currently selected item.
  2. a (initially hidden) div which contains the items in the dropdown menu.
  3. an icon to indicate the state of the dropdown (open or closed). Note that the svg used is adapted from Bootstrap icons.

Business logic

  1. When connected, display the component in its selected theme. Choose the default one if none is selected.
  2. Register the dropdown and item selected events passed when declaratively creating the component.
  3. Once the dropdown event is fired, capture the items and add them to the list.
  4. Give the ability to set the selected item programatically. This is particularly useful when the currently selected item is pre-known for the service provider. For instance, a list of locations in a booking site and it should ideally display the current city at which the user resides.

How it looks

Dropdown Component in Codepen

Conclusion

We created a modern customizable dropdown component using the tools available to the browser and it looks the same everywhere. Feel free to let me know if you have any additions or questions.

Happy developing!

Top comments (0)