This content originally appeared on DEV Community and was authored by Alfie Jones
Having a Dark and Light mode to your website is becoming more and more popular. I'm proud to say I have build an opensource project which provides a collection of elegant and functional toggles.
The library currently has official support for React but can be easily used in any framework.
Adding to a website
I'm going to show you how to add the Classic toggle to a website. If you're using react, see below.
Firstly, we need to copy the HTML code, from toggles.dev
We're going to use the button, and at the time of writing it looks like this:
<button
class="theme-toggle"
type="button"
title="Toggle theme"
aria-label="Toggle theme"
>
<svg
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
width="1em"
height="1em"
fill="currentColor"
stroke-linecap="round"
class="theme-toggle__classic"
viewBox="0 0 32 32"
>
<clipPath id="theme-toggle__classic__cutout">
<path d="M0-5h30a1 1 0 0 0 9 13v24H0Z" />
</clipPath>
<g clip-path="url(#theme-toggle__classic__cutout)">
<circle cx="16" cy="16" r="9.34" />
<g stroke="currentColor" stroke-width="1.5">
<path d="M16 5.5v-4" />
<path d="M16 30.5v-4" />
<path d="M1.5 16h4" />
<path d="M26.5 16h4" />
<path d="m23.4 8.6 2.8-2.8" />
<path d="m5.7 26.3 2.9-2.9" />
<path d="m5.8 5.8 2.8 2.8" />
<path d="m23.4 23.4 2.9 2.9" />
</g>
</g>
</svg>
</button>
We then want to make sure we have the CSS. Find the latest versions from JSDELIVR and add it to your Head.
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/theme-toggles@4.9.2/css/classic.min.css" integrity="sha256-ILVFUnh+ImxX+Mn4ykqVnowo8WNCuskhdKSuoOOrago=" crossorigin="anonymous">
<head />
Now all we need to do is apply the toggled class when the theme is dark. The button will toggle when it has the class "theme-toggle--toggled". This should be toggled via JavaScript.
And that's it.
React
If you're using react, it's even easier to get the toggles up and running. See how to use the react package here
This content originally appeared on DEV Community and was authored by Alfie Jones
Alfie Jones | Sciencx (2022-03-24T16:25:58+00:00) Adding an Animated Dark Theme Toggle to your website. Retrieved from https://www.scien.cx/2022/03/24/adding-an-animated-dark-theme-toggle-to-your-website/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.