A Web Component to set a site-wide theme preference using a native select element, saved to local storage.
MIT License
theme-selector
A Web Component for setting a website theme using a select element.
General usage example:
<script type="module" src="theme-selector.js"></script>
<theme-selector>
<select autocomplete="off">
<option value="light">
Light
</option>
<option value="dark">
Dark
</option>
</select>
</theme-selector>
<style>
theme-selector:not(:defined) {
display: none;
}
</style>
Example using a custom storage key:
<script type="module" src="theme-selector.js"></script>
<theme-selector data-key="color-scheme">
<select autocomplete="off">
<option value="light">
Light
</option>
<option value="dark">
Dark
</option>
</select>
</theme-selector>
<style>
theme-selector:not(:defined) {
display: none;
}
</style>
Example using a custom dark theme key:
<script type="module" src="theme-selector.js"></script>
<theme-selector data-dark-theme="white-on-black">
<select autocomplete="off">
<option value="black-on-white">
Black on White
</option>
<option value="white-on-black">
White on Black
</option>
</select>
</theme-selector>
<style>
theme-selector:not(:defined) {
display: none;
}
</style>
Example with a custom transition class and duration to keep the class applied:
<script type="module" src="theme-selector.js"></script>
<theme-selector data-transition-class="transitioning" data-transition-duration="100">
<select autocomplete="off">
<option value="light">
Light
</option>
<option value="dark">
Dark
</option>
</select>
</theme-selector>
<style>
theme-selector:not(:defined) {
display: none;
}
</style>
Example targeting a specific element to apply the theme to:
<script type="module" src="theme-selector.js"></script>
<theme-selector data-root-element=".content">
<select autocomplete="off">
<option value="light">
Light
</option>
<option value="dark">
Dark
</option>
</select>
</theme-selector>
<style>
theme-selector:not(:defined) {
display: none;
}
</style>
This Web Component allows you to use a select element to control user-preferred theming across your website by setting a data attribute against the root element (or a defined selector query). Additionally saves the preference to local storage so that it can be applied on new page loads and maintained between user visits.
You have a few options (choose one of these):
npm install @chrisburnell/theme-selector
Make sure you include the <script>
in your project (choose one of these):
<!-- Host yourself -->
<script type="module" src="theme-selector.js"></script>
<!-- 3rd party CDN, not recommended for production use -->
<script
type="module"
src="https://www.unpkg.com/@chrisburnell/theme-selector/theme-selector.js"
></script>
<!-- 3rd party CDN, not recommended for production use -->
<script
type="module"
src="https://esm.sh/@chrisburnell/theme-selector"
></script>
With thanks to the following people: