theme-change

repository·master·Indexed 23 days ago

https://github.com/saadeghi/theme-change

A tiny helper for managing CSS themes using CSS Variables and localStorage. It allows developers to switch themes via HTML attributes on buttons, selects, and checkboxes, persisting user choices and synchronizing multiple controls across a page. Supports integration with React, Vue, Svelte, and Astro, and provides functionality to manage active states using data-act-class and data-act-attribute.

Tokens
3.1K
Snippets
5
Records
27
Agent score
81%

What's inside theme-change

  1. Configure CSS theme tokens

    master

    The library works by setting a data-theme attribute on the document. You can use existing theme systems like daisyUI or define your own CSS variables mapped to specific theme names.

    :root {
      --my-color: #fff;
    }
    [data-theme="dark"] {
      --my-color: #000;
    }
    [data-theme="pink"] {
      --my-color: #ffabc8;
    }
    body {
      background-color: var(--my-color);
    }
  2. Use HTML patterns for theme controls

    master

    Use the data-set-theme attribute on various HTML elements to create theme switchers. The library persists the selection in localStorage and syncs all matching controls.

    Control TypeHTML PatternBehavior
    Button (Single)<button data-set-theme="dark">Dark</button>Sets theme to 'dark'
    Button (Rotate)<button data-set-theme="dark,light,pink">Rotate</button>Cycles through themes on each click
    Select<select data-set-theme><option value="">Default</option><option value="dark">Dark</option></select>Sets theme based on selected option value
    Checkbox<input type="checkbox" value="dark" data-set-theme />Checked sets theme; unchecked clears it
    <!-- Button set -->
    <button data-set-theme="dark">Dark</button>
    
    <!-- Button rotate -->
    <button data-set-theme="dark,light,pink">Rotate</button>
    
    <!-- Select -->
    <select data-set-theme>
      <option value="">Default</option>
      <option value="dark">Dark</option>
    </select>
    
    <!-- Checkbox -->
    <input type="checkbox" value="dark" data-set-theme />
  3. Integrate theme-change with React, Vue, Svelte, or Astro

    master

    When using modern frameworks, initialize theme-change within the component lifecycle hooks to handle dynamic mounting.

    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>
  4. Install theme-change via CDN or NPM

    master

    You can include theme-change in your project using a CDN script tag or by installing it via NPM.

    CDN

    Add the following script tag to your HTML:

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

    NPM

    Install the package using npm:

    npm i theme-change@latest
  5. Configure theme toggles using data attributes

    master

    To create a theme switcher, add the data-toggle-theme attribute to your HTML elements. The library uses this attribute to determine which themes to cycle through and which storage key to use for persistence.

    Key attributes used by the toggle logic:

    • data-toggle-theme: A space-separated list of themes to cycle through (e.g., "light dark").
    • data-act-class: (Optional) A CSS class to toggle on the element when its primary theme is active.
    • data-act-attribute: (Optional) An attribute to update to indicate the active state.
  6. Initialize theme-change

    master

    To activate theme switching, call the themeChange() function.

    Important: If your theme controls (buttons, selects, etc.) are mounted dynamically after the initial page load (e.g., in a Single Page Application), call themeChange(false) to ensure the library scans the DOM for the new elements.

    import { themeChange } from "theme-change";
    
    themeChange();
    
    // Use false if controls are mounted after initial load
    themeChange(false);
  7. Manage active states with `data-act-class` and `data-act-attribute`

    master

    You can automatically apply classes or attributes to buttons when their assigned theme is currently active. These options are button-only and are ignored on <select> and <input> elements.

    data-act-class

    Adds a specific CSS class to the button when its theme is active.

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

    data-act-attribute

    Sets an arbitrary HTML attribute (instead of a class) when active. This is useful for accessibility (e.g., aria-pressed).

    • With value: Use name:value syntax. The first colon is the separator. Example: aria-pressed:true sets aria-pressed="true" when active and removes it when inactive.
    • Boolean presence: Use just the name. Example: aria-current adds aria-current="" when active and removes it when inactive.
    <!-- Sets aria-pressed="true" when active -->
    <button data-set-theme="dark" data-act-attribute="aria-pressed:true"></button>
    
    <!-- Adds aria-current="" when active -->
    <button data-set-theme="pink" data-act-attribute="aria-current"></button>
    <button data-set-theme="" data-act-class="ACTIVE"></button>
    <button data-set-theme="dark" data-act-class="ACTIVE"></button>
    <button data-set-theme="dark" data-act-attribute="aria-pressed:true"></button>
    <button data-set-theme="pink" data-act-attribute="aria-current"></button>
  8. Sync multiple controls with `data-key`

    master
    By default, all controls with data-set-theme are synced. If you want to have multiple independent theme switchers on one page (e.g., one for the main site and one for an admin panel), use the data-key attribute to group them.
  9. Initialize theme change with themeBtn()

    master
    Call themeBtn() to immediately initialize the theme change logic. This is useful if you are manually controlling when the theme initialization occurs, for example, in an environment where the DOM is already loaded.
  10. Use themeChange() to toggle themes

    master
    Call themeChange() to toggle the current theme. If you pass true to the attach parameter, the function will automatically attach a click event listener to all elements with the data-theme-change attribute. If false or omitted, you must manually attach event listeners to your theme-switching elements.
  11. Use themeSelect() to set a specific theme

    master
    Call themeSelect() to trigger the theme selection logic. This is typically used when you want to programmatically switch to a specific theme based on user interaction or application state, relying on the attributes defined on the element that triggered the selection.