theme-change
Version:
Change CSS theme with toggle, buttons or select using CSS Variables and localStorage
80 lines (64 loc) • 2.51 kB
Markdown
Only 2KB minified (400 bytes GZipped)
Change CSS theme with toggle, buttons or select using CSS Variables ([CSS custom properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*)) and [localStorage](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
It saves the chosen theme in brower localStorage and loads it again when page loads.
You only need to define your theme in CSS
See in action 👉 https://codepen.io/saadeghi/pen/OJypbNM
Sample Site 👉 https://css-theme-changer.netlify.app/

## 👨💻 How to use ##
1️⃣ JS:
Method 1 - Use CDN:
```
<script src="https://unpkg.com/theme-change"></script>
```
Method 2 - NPM:
Install: ` npm i theme-change --save` and import to your js file and call it:
```
import {themeBtn, themeToggle, themeSelect} from "theme-change"
themeBtn() // if you want to change theme with buttons
themeToggle() // if you want to change theme with a toggle
themeSelect() // if you want to change theme with a <select>
```
2️⃣ CSS: Set your themeable style as custom properties in CSS like this:
```
:root {
--color-default:
/* or any other variables */
}
[] {
--color-default:
}
[] {
--color-default:
}
/* and use your variables on any element */
body {
background-color: var(--color-default);
}
```
3️⃣ HTML: Use one of these data attributes to change the theme 👇
Using `data-toggle-theme`
Clicking on this button, toggles between the default theme and `dark` theme and applies the `ACTIVECLASS` when `dark` theme is active
```
<button data-act-class="ACTIVECLASS" data-toggle-theme="dark"></button>
```
Using `data-set-theme`
Clicking on these buttons, sets the chosen theme and also sets the `ACTIVECLASS` for the chosen button
```
<button data-act-class="ACTIVECLASS" data-set-theme="">Default</button>
<button data-act-class="ACTIVECLASS" data-set-theme="dark">Dark</button>
<button data-act-class="ACTIVECLASS" data-set-theme="pink">Black</button>
```
Using `data-choose-theme`
Simply choose the theme
```
<select data-choose-theme>
<option value="">Default</option>
<option value="dark">Dark</option>
<option value="pink">Pink</option>
</select>
```