DEV Community

Cover image for Modern Dropdown component HTML
Amjad Abujamous
Amjad Abujamous

Posted on • Edited on

1

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay