Skip to content

saadeghi/theme-change

Repository files navigation

🎨 CSS Theme Change

Tiny helper for CSS themes.

  • One HTML attribute data-set-theme to set theme theme.
  • Works with button, select, and checkbox
  • Persists theme in localStorage
  • Syncs all matching data-set-theme controls

Demo

image

Quick start

CDN

<script src="https://cdn.jsdelivr.net/npm/theme-change@latest/index.js"></script>

NPM

npm i theme-change@latest
import { themeChange } from "theme-change";

themeChange();

Use themeChange(false) when controls are mounted after initial page load.

Framework snippets

React
import { useEffect } from "react";
import { themeChange } from "theme-change";

useEffect(() => {
  themeChange(false);
}, []);
Vue
import { onMounted } from "vue";
import { themeChange } from "theme-change";

export default {
  setup() {
    onMounted(() => {
      themeChange(false);
    });
  },
};
Svelte
import { onMount } from "svelte";
import { themeChange } from "theme-change";

onMount(() => {
  themeChange(false);
});
Astro
---
import { themeChange } from "theme-change";
---

<script>
  themeChange(false);
</script>

CSS setup

Use daisyUI themes, or define your own theme tokens:

:root {
  --my-color: #fff;
}
[data-theme="dark"] {
  --my-color: #000;
}
[data-theme="pink"] {
  --my-color: #ffabc8;
}
body {
  background-color: var(--my-color);
}

HTML patterns

Pattern Preview Minimal code
Button set button theme <button data-set-theme="dark">Dark</button>
Button rotate button rotate <button data-set-theme="dark,light,pink">Rotate</button>
Select select theme <select data-set-theme><option value="">Default</option><option value="dark">Dark</option></select>
Checkbox checkbox theme <input type="checkbox" value="dark" data-set-theme />

Notes:

  • For checkbox: checked sets theme, unchecked clears theme.
  • For rotate button: each click moves to the next item and loops.
  • Controls with the same data-key stay in sync.

Optional attributes

data-act-class

<button data-set-theme="" data-act-class="ACTIVE"></button>
<button data-set-theme="dark" data-act-class="ACTIVE"></button>
<button data-set-theme="pink" data-act-class="ACTIVE"></button>

data-key

<select data-set-theme data-key="admin-panel"></select>
<button data-set-theme="dark" data-key="front-page"></button>
<input type="checkbox" value="pink" data-set-theme data-key="premium-user-theme" />

Backward compatibility

Legacy v2 attributes still work:

  • data-toggle-theme
  • data-choose-theme

About

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

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

Contributors