Custom Single Select Box In Vanilla JavaScript – FancySelect

Category: Form , Javascript | February 2, 2023
Author:mdbassit
Views Total:18 views
Official Page:Go to website
Last Update:February 2, 2023
License:MIT

Preview:

Custom Single Select Box In Vanilla JavaScript – FancySelect

Description:

FancySelect is a JavaScript library that turns a single select element into a customizable, fully accessible dropdown list.

More Features:

  • Supports icons.
  • Auto re-position to prevent overflowing.
  • Allows to add new options dynamically.

How to use it:

1. Import the stylesheet fancyselect.min.css and JavaScript fancyselect.min.js.

<script type="text/javascript" src="fancyselect.min.js"></script>
<link rel="stylesheet" type="text/css" href="fancyselect.min.css" />

2. That’s it. The library will automatically apply custom styles to the native select elements found within the document.

<select id="default">
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
  ...
</select>

3. Apply your own styles to the select.

<select id="custom">
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
  ...
</select>
.custom {
  --fsb-border: 0;
  --fsb-radius: 2em;
  --fsb-color: #fff;
  --fsb-background: #2F86A6;
  --fsb-font-size: 1em;
  --fsb-shadow: 0 1px 1px rgba(0, 0, 0, .1);
  --fsb-padding: .75em 1.5em;
  --fsb-arrow-padding: 1.5em;
  --fsb-arrow-size: .5em;
  --fsb-arrow-color: currentColor;
  --fsb-icon-color: currentColor;
  --fsb-list-height: 200px;
  --fsb-list-border: var(--fsb-border);
  --fsb-list-radius: .75em;
  --fsb-list-color: var(--fsb-color);
  --fsb-list-background: #34BE82;
  --fsb-hover-color: var(--fsb-color);
  --fsb-hover-background: #2FDD92;
}

4. Add icons to options.

<select id="default">
  <option data-icon="1.svg">Option 1</option>
  <option data-icon="2.svg">Option 2</option>
  <option data-icon="3.svg">Option 3</option>
  ...
</select>

5. Add new options to the custom element.

const mySelect = document.getElementById('my-select');
const newItems = ['Option4', 'Option5', 'Option6'];
newItems.forEach(item => {
  const option = document.createElement('option');
  option.textContent = item;
  mySelect.appendChild(option); 
});
// Update the custom select
FancySelect.update(mySelect);

6. Disable the native select element.

mySelect.disabled = true;

Changelog:

v0.4.0 (02/02/2023)

  • Improve the display of long labels
  • Add support for an optional custom item label renderer
  • Fix a bug where the list box occupies space when closed

v0.3.3 (01/01/2023)

  • Add type=”button” to button elements

v0.3.2 (10/31/2022)

  • Bugfix

v0.3.1 (10/26/2022)

  • Fix a bug when closing the list box on a second click

v0.3.0 (10/24/2022)

  • Close the list box on a second click

You Might Be Interested In:


Leave a Reply