Dark Mode in Tailwind
There are two ways to set up dark mode (class or media).
I chose the 'class' approach. To do this, I updated the darkMode setting in the tailwind.config.js file:
module.exports = {
content: ["./views/**/*.{html,js,ejs}"],
presets: [],
darkMode: 'class', // <<<<<< I changed this to 'class'
theme: {
Now, the way things will work is this: If the BODY element on the page has a class of dark then the page will use all the dark: settings.
In order to toggle the dark class on the BODY element, I added a button to the page, and here is the event handler code I used for it:
// DARK MODE TOGGLING
const darkModeBtn = document.querySelector("#dark-mode-button");
darkModeBtn.addEventListener("click", () => {
document.body.classList.toggle('dark')
})
It simply toggles the dark class on the BODY element.
Once you've got it all set up, you just need to specify the dark mode settings in your styling:
<div class="text-black bg-white dark:bg-black dark:text-white">
</div>
If you want to remember the user's preference, you can use localStorage for that. Just replace the JavaScript with this:
// DARK MODE TOGGLING (with local storage!)
if(localStorage.getItem('theme') === 'dark'){
document.body.classList.add("dark");
}
const darkModeBtn = document.querySelector("#dark-mode-button");
darkModeBtn.addEventListener("click", () => {
document.body.classList.toggle('dark')
if(document.body.classList.contains("dark")){
localStorage.setItem('theme','dark')
}else{
localStorage.setItem('theme', null)
}
})