How to sync Dark Mode to all the pages on a website

I made it so that their is a little button on the bottom right of my website that can switch between dark and light mode. Light mode is the default. When I switch to another page and it is in dark mode, the dark mode doesn’t stay and it changes back to the default light mode. Is their a way that I can make it so that it stays as dark mode until you switch it back? Here is the codepen so that you can see my code.

Off the top of my head,

  1. Have a variable for preferred mode, then
  2. a. Set/get cookies
    b. Use backend (Node, Django, other)
    c. Use React / state (not sure about this depends on app / page structure.) It seems like your “pages” are just changes to text of elements within the page, which means it should work with React on a single page.

Oh god that seems complicated. Is their a tutorial to do the cookie method? It seems the easiest.

I removed the switcher as dark mode looks way better

If you do go back to it:

Save some key (like "mode": "dark") to local storage, the JavaScript should check that key as the first thing it does, and switch based on that.

Cookie if you want to persist it when a user comes back to the site (ie new session) but local storage is very simple and will work fine.

Dan, thanks I hadn’t thought of that.

Toast, if you’re still reading, Google says: (cookie approach) (local storage)

1 Like