Skip to content

Instantly share code, notes, and snippets.

@jacobobryant
Last active August 28, 2023 19:34
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jacobobryant/14834ada08b00242b28c2b36f4c0225d to your computer and use it in GitHub Desktop.
How to add a toggle button for dark mode with Biff and Tailwind

How to add a toggle button for dark mode with Biff and Tailwind

By default, Tailwind's dark mode classes will take effect automatically if the user's operating system is already set to dark mode. Follow these instructions if you would also like to provide a toggle button so the user can override the operating system setting.

Set darkMode: 'class' in tailwind.config.js:

module.exports = {
  darkMode: 'class',
  // ...
}

Add the provided darkmode.js file to resources/darkmode.js. Inline it into your HTML so that it runs immediately when the page loads:

(defn some-page [ctx]
  (biff/base-html
   (merge ctx {:base/head [[:script (biff/unsafe (slurp (io/resource "darkmode.js")))]]})
   ...))

Then add a button to your UI that calls toggleDarkMode():

[:button {:onclick "toggleDarkMode()"} "Toggle"]
// Adapted from https://tailwindcss.com/docs/dark-mode#supporting-system-preference-and-manual-selection
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
document.documentElement.classList.add('dark')
} else {
document.documentElement.classList.remove('dark')
}
var darkModeOn = document.documentElement.classList.contains('dark');
function toggleDarkMode () {
if (darkModeOn) {
document.documentElement.classList.remove('dark');
localStorage.theme = 'light';
} else {
document.documentElement.classList.add('dark');
localStorage.theme = 'dark';
}
darkModeOn = !darkModeOn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment