Toggle Between Dark & Light Modes With The Theme Toggle Web Component

Category: Javascript | May 30, 2024
Author:cdransf
Views Total:18 views
Official Page:Go to website
Last Update:May 30, 2024
License:MIT

Preview:

Toggle Between Dark & Light Modes With The Theme Toggle Web Component

Description:

theme-toggle is a lightweight web component that enables users to switch between dark and light themes of your site with the click of a button.

It allows you to define light and dark modes using CSS custom properties and CSS media queries. By adding the theme__light or theme__dark classes to the document dynamically, you can alter colors, backgrounds, and other styles without having to rewrite CSS. This keeps your code DRY and maintainable.

How to use it:

1. Import the Theme Toggle Web Component into your document.

<script type="module" src="theme-load.js"></script>
<script type="module" src="theme-toggle.js"></script>

2. Add a toggle button to the theme-toggle component.

<theme-toggle>
  <button
    class="theme__toggle"
    aria-label="Toggle site theme">
    <span class="light">
      🌞
    </span>
    <span class="dark">
      🌑
    </span>
  </button>
</theme-toggle>

3. Apply the following CSS styles to the theme-toggle component to make it more accessible.

.theme__toggle {
  background: transparent;
  padding: 0;
  border: 0;
}
.theme__toggle > .light ,
.theme__toggle > .dark {
  display: none;
}
.theme__dark .theme__toggle > .light {
  display: inline;
}
.theme__dark .theme__toggle > .dark {
  display: none;
}
.theme__light .theme__toggle > .light {
  display: none;
}
.theme__light .theme__toggle > .dark {
  display: inline;
}

4. Define your light and dark theme styles using CSS variables and let the component handle the switching logic.

/* base theme */
:root {
  --color-lightest: #fafaf7;
  --color-darkest: #222222;
}
/* dark theme */
@media (prefers-color-scheme: dark) {
  :root {
    color: var(--color-lightest);
    background-color: var(--color-darkest);
  }
}
/* light theme */
:root.theme__light {
  color: var(--color-darkest);
  background-color: var(--color-lightest);
}
/* dark theme */
:root.theme__dark {
  color: var(--color-lightest);
  background-color: var(--color-darkest);
}

Changelog:

v1.3.2 (05/30/2024)

  • code cleanup

You Might Be Interested In:


Leave a Reply