Light Dark Switch
A color theme switcher based on the user system preferences.
Projects /
A color theme switcher based on the user system preferences.
The light/dark component controls the color theme of your website. It supports 3 appearances: light, dark, and 'system' (i.e., it depends on the user system preferences).
Behind the scene, this component is a <select>
element. Make sure the data-option-theme
values are equal to your light/dark color theme names.
<div class="adv-select js-adv-select js-ld-switch">
<select>
<optgroup label="Appearance">
<option value="0" data-option-theme="default">Light</option>
<option value="1" data-option-theme="dark">Dark</option>
<option value="2">System</option>
</optgroup>
</select>
<!-- ... -->
</div>
To customize the appearance of the <option>
elements, we're using the Advanced Custom Select component.
If you need to customize the .ld-switch-btn__icon
elements, make sure to preserve their order (light, dark, system light and system dark).
When a color theme is selected, the component adds to the HTML
element a data-theme
attribute equal to the color theme name (e.g., data-theme="dark"
).
If you need to apply that attribute to a different DOM element (e.g., the <body>
), you can modify the updateThemeValue
function in the light-dark-switch.js file.
The Local Storage API is used to store the theme selection. The ldSwitch
data item is added to the localStorage property when a theme selection is made (possible values are light/dark color theme names and 'system').
On page reload, you can check if the ldSwitch
item is set and apply a color theme accordingly:
var themeSelection = localStorage.getItem('ldSwitch');