0.1.5 • Published 2 years ago

@andystevenson/theme-toggle v0.1.5

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

a simple javascript/css solution for toggling light/dark themes on websites


Highlights

  • Totally inspired by Adam Argyle based on his GUI Challenges over at web.dev (theme switching component)
  • Simple library
  • Links to user prefers-color-scheme OS settings
  • Writes to browser localStorage to remember user preferences

Install

npm install @andystevenson/theme-toggle

Usage

import toggle from '@andystevenson/theme-toggle'

.... that's it!

Styling it with CSS
[data-theme='light'] {
  color-scheme: light;
  background-color: antiquewhite;
  color: darkslategray;
}

[data-theme='dark'] {
  color-scheme: dark;
  background-color: darkslategray;
  color: antiquewhite;
}

html[data-theme='dark'] [data-theme='light'].theme-toggle,
html[data-theme='light'] [data-theme='dark'].theme-toggle {
  display: none;
}
Linking it into your HTML
<head>
  <script type="module" src="./theme-toggle.js"></script>
  <!-- assuming theme-toggler.js would do the following -->
  <!-- import toggle from '@andystevenson/theme-toggle' -->
  ...
</head>

The rationale for doing it like this

Quoting from Adam Argyle... To achieve this, a plain <script> tag in the document <head> is loaded first, before any CSS or <body> markup. When the browser encounters an unmarked script like this, it runs the code and executes it before the rest of the HTML. Using this blocking moment sparingly, it's possible to set the HTML attribute before the main CSS paints the page, thus preventing a flash or colors.

Under the covers

To make the toggle work the HTML page must contain a clickable element with id="theme-toggler" (can be anything... even a div).

What happens when user clicks/selects the theme-toggler is an attribute data-theme' is attached to the <html> document tag. What the theme-toggle library is doing is switching between data-theme='dark' and data-theme='light'. How you then style these is up to you. See the trivial CSS above as an example. Have a look at the git hub repo for a full example with a working index.html example. The package.json uses as the bundler.

Credits

All credit to Adam Argyle for the inspiration.

I used a couple of SVG icons from the very useful Bootstrap Icons Library.

License

MIT

Maintainer