The CustomSelect component is a JavaScript class that transforms standard HTML <select> elements into customizable dropdown UIs. This component enhances the visual appearance and functionality of select menus without altering their underlying behavior.
First, ensure you have imported both the JavaScript and SCSS files in your project:
// Import CustomSelect class
import CustomSelect from './CustomSelect.js';
// Import custom styles
import './custom-select.scss';Create an instance of CustomSelect by passing a CSS selector string that targets the <select> elements you want to customize:
document.addEventListener('DOMContentLoaded', () => {
const customSelect = new CustomSelect('.my-select-class');
});Replace .my-select-class with the appropriate class or ID of your select elements.
The component provides a customizable dropdown UI with styles for:
- Selected options
- Disabled options
- Dropdown visibility
- Scrollbars
- Label Update: Automatically updates the label text to reflect the selected option.
- Dropdown Toggle: Toggles the dropdown list when the label is clicked.
- Option Selection: Updates both the custom UI and the original
<select>element when an option is chosen. - Outside Click Close: Closes the dropdown when clicking outside of it.
Here's a simple example of how to use the CustomSelect component:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="path/to/custom-select.scss">
<title>CustomSelect Example</title>
</head>
<body>
<select class="my-select-class">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3" disabled>Disabled Option</option>
</select>
<script type="module">
// Import CustomSelect class
import CustomSelect from './CustomSelect.js';
document.addEventListener('DOMContentLoaded', () => {
const customSelect = new CustomSelect('.my-select-class');
});
</script>
</body>
</html>In this example, the CustomSelect component is initialized on a select element with the class .my-select-class, enhancing its appearance and functionality as described.
- Ensure that the paths to your SCSS and JavaScript files are correct.
- Customize the styles in
custom-select.scssto match your design requirements.