How to toggle dark mode with a button in JavaScript?

Hey everyone! I’ve got this cool dark mode feature on my website using CSS. It works great with a keyboard shortcut, but now I want to add a button to switch it on and off. Here’s what I’ve got so far:

.night-theme {
  filter: invert(100%) hue-rotate(180deg);
}

.flip-colors {
  filter: invert(100%) hue-rotate(180deg);
}

And my JavaScript:

document.addEventListener('keydown', function(event) {
  if (event.key === 'Enter') {
    document.documentElement.classList.toggle('night-theme');
    document.querySelectorAll('.color-flip').forEach(item => {
      item.classList.toggle('flip-colors');
    });
  }
});

This works fine when I press Enter, but I’m stuck on how to make it work with a button click. Any ideas on how to modify this code to work with a button instead? Thanks for your help!

I’ve implemented something similar on my site, and here’s what worked for me:

First, add a button to your HTML:

<button id="darkModeToggle">Toggle Dark Mode</button>

Then, modify your JavaScript like this:

function toggleDarkMode() {
    document.documentElement.classList.toggle('night-theme');
    document.querySelectorAll('.color-flip').forEach(item => {
        item.classList.toggle('flip-colors');
    });
}

document.getElementById('darkModeToggle').addEventListener('click', toggleDarkMode);

// Keep the keyboard shortcut if you want
document.addEventListener('keydown', function(event) {
    if (event.key === 'Enter') {
        toggleDarkMode();
    }
});

This way, clicking the button or pressing Enter will both trigger the same function. It’s clean and easy to maintain. Hope this helps!

hey liam, i got u covered! just add this to ur js:

const btn = document.querySelector('#darkModeBtn');
btn.addEventListener('click', () => {
  document.documentElement.classList.toggle('night-theme');
  document.querySelectorAll('.color-flip').forEach(el => el.classList.toggle('flip-colors'));
});

dont forget to add the button in ur html. ez pz!

I’ve implemented a similar feature using a different approach that might be worth considering. Instead of toggling classes, I used CSS custom properties (variables) to manage the color scheme. Here’s a simplified version:

const root = document.documentElement;
const toggleButton = document.getElementById('darkModeToggle');

toggleButton.addEventListener('click', () => {
  root.style.setProperty('--bg-color', root.style.getPropertyValue('--bg-color') === '#fff' ? '#333' : '#fff');
  root.style.setProperty('--text-color', root.style.getPropertyValue('--text-color') === '#333' ? '#fff' : '#333');
});

This approach allows for more granular control over individual colors and can be easier to maintain as your site grows. It also avoids potential issues with the invert filter affecting images or other elements unexpectedly.