A lightweight jQuery plugin that replaces native select elements with customizable dropdowns.
Download View on GitHub1. Include jQuery and the plugin.
<script src="path/to/jquery.js"></script>
<script src="path/to/jquery.nice-select.js"></script>
2. Include the plugin styles, either the compiled CSS...
<link rel="stylesheet" href="path/to/nice-select.css">
...or, ideally, import the SASS source (if you use SASS) in your main stylesheet for easier customization.
@import 'nice-select'; // Or 'nice-select-prefixed'. See 'Notes' section.
3. Finally, initialize the plugin.
$(document).ready(function() {
$('select').niceSelect();
});
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>
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.
$('select').niceSelect('update');
Removes the custom dropdown and unbinds all its events.
$('select').niceSelect('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.