Custom Single Select Box In Vanilla JavaScript – FancySelect

Category: Form , Javascript | November 25, 2021
Author:mdbassit
Views Total:24 views
Official Page:Go to website
Last Update:November 25, 2021
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;

You Might Be Interested In:


Leave a Reply