A lightweight vanilla javascript library that replaces native select elements with customizable dropdowns.
Download View on GitHub1. Include the library.
<script src="path/to/nice-select2.js"></script>
2. Include the plugin styles, either the compiled CSS...
<link rel="stylesheet" href="path/to/nice-select2.css">
...or, ideally, import the SASS source (if you use SASS) in your main stylesheet for easier customization.
@import 'nice-select2'; // Or 'nice-select-prefixed'. See 'Notes' section.
3. Finally, initialize the plugin.
NiceSelect.bind(document.getElementById("#a-select"));
All done. That will turn this:
...into this:
There are no settings (a native select doesn't have settings), although there are a couple of special features, documented below.
You can specify an alternate text for each option, which will be displayed on the dropdown when that option is selected.
Add a data-display
attribute to the desired options. For example:
<select>
<option data-display="Select">Nothing</option>
<option value="1">Some option</option>
<option value="2">Another option</option>
<option value="3" disabled>A disabled option</option>
<option value="4">Potato</option>
</select>
Updates the custom dropdown to reflect any changes made to the original select element.
var options = {searchable: true};
NiceSelect.bind(document.getElementById("seachable-select"), options);
Translate the three different texts: 'Select an option', 'Search', 'selected'
var options = {searchable: true, placeholder: 'select', searchtext: 'zoek', selectedtext: 'geselecteerd'};
NiceSelect.bind(document.getElementById("seachable-select"), options);
Every class you assign to a select element will be copied to the generated dropdown. That way you can customize different versions of it to your needs just by adding new CSS.
These are some examples included in the plugin stylesheet:
Updates the custom dropdown to reflect any changes made to the original select element.
var instance = NiceSelect.bind(...);
instance.update();
Removes the custom dropdown and unbinds all its events.
var instance = NiceSelect.bind(...);
instance.destroy();
Autoprefixer is used to add vendor prefixes to CSS rules for older browser support. A nice-select-prefixed.scss file is also generated if you wish to include the SASS file in your project and you're not using Autoprefixer.
In some cases there can be a brief flash in which the native selects are displayed—between the time the page is loaded and the scripts are run. This can be fixed by adding a CSS rule to hide them beforehand:
select {
display: none;
}
Note that the above rule will hide all native select elements. If you're only applying the plugin to some select elements you should adapt the rule accordingly.