JSPM

  • Created
  • Published
  • Downloads 13503
  • Score
    100M100P100Q125252F
  • License ISC

Change CSS theme with toggle, buttons or select using CSS Variables and localStorage

Package Exports

  • theme-change

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (theme-change) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

🎨 CSS Theme Changer

Only 2KB minified (400 bytes GZipped)

Change CSS theme with toggle, buttons or select using CSS Variables (CSS custom properties) and 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/

image

👨‍💻 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: #fff;
  /* or any other variables */
}
[data-theme='dark'] {
  --color-default: #252b30;
}
[data-theme='pink'] {
  --color-default: #ffabc8;
}
/* 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 👇

✅ Toggle

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>

✅ Buttons

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>

✅ Select

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>