Blog>
Snippets

Theme Switcher Plugin

Build a plugin that allows users to toggle between light and dark themes, showing how to manage and apply theme-related CSS variables.
<!-- HTML: Place this in your HTML where you want the theme switcher to appear -->
<button id="theme-switcher">Switch Theme</button>
This is the HTML for the theme switcher button. Place this in your webpage where you wish users to be able to switch themes.
/* CSS: Define the CSS variables for light and dark themes and set default theme */
:root {
    --background-color: #ffffff;
    --text-color: #000000;
}

[data-theme="dark"] {
    --background-color: #000000;
    --text-color: #ffffff;
}

body {
    background-color: var(--background-color);
    color: var(--text-color);
}
These are the CSS rules for light and dark themes using CSS variables. The default theme is light. When the data-theme attribute is set to dark on the root element, the dark theme's CSS variables are applied.
// JavaScript: Theme switcher functionality
document.addEventListener('DOMContentLoaded', (event) => {
    const switcher = document.getElementById('theme-switcher');
    switcher.addEventListener('click', () => {
        const theme = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
        document.documentElement.setAttribute('data-theme', theme);
    });
});
This JavaScript code handles the click event on the theme switcher button. It toggles the data-theme attribute between light and dark on the root element, causing the page to switch themes using the defined CSS variables.