DEV Community

Cover image for Adding an Animated Dark Theme Toggle to your website
Alfie Jones
Alfie Jones

Posted on

Adding an Animated Dark Theme Toggle to your website

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.

All the toggles

Github

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>
Enter fullscreen mode Exit fullscreen mode

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 />
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)