So, I have a dark mode button that works fine when light mode is enabled but if I use the auto detect css media query and page starts in darkmode the button will not do anything because it's already in dark mode. My question is how can I make the same darkmode button work and switch page to light mode instead of adding a sperate button for light mode?
HTML
<button onclick="dark_mode()"> dark mode </button>
CSS
.dark-mode {
css code for dark mode here
}
JS
function dark_mode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
So, I have a dark mode button that works fine when light mode is enabled but if I use the auto detect css media query and page starts in darkmode the button will not do anything because it's already in dark mode. My question is how can I make the same darkmode button work and switch page to light mode instead of adding a sperate button for light mode?
HTML
<button onclick="dark_mode()"> dark mode </button>
CSS
.dark-mode {
css code for dark mode here
}
JS
function dark_mode() {
var element = document.body;
element.classList.toggle("dark-mode");
}
Share
Improve this question
asked Feb 14 at 20:13
user29519291user29519291
12 bronze badges
3
|
1 Answer
Reset to default 1Lets start with finding out what mode the user prefers:
let isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
A better name for this function could be toggleColorScheme
<button onclick="toggleColorScheme()"> Toggle color scheme </button>
Lets define the function. Make sure it can access isDarkMode
.
const toggleColorScheme = () => {
isDarkMode ^= 1 // Toggle `isDarkMode` between 0 and 1
if (isDarkMode) document.body.classList.add('dark-mode');
else document.body.classList.remove('dark-mode');
}
I disrecommend using classList.toggle()
as you don't have 100% certainty over when the .dark-mode
class is present or not.
@media (prefers-color-scheme: dark)
it has nothing to do with a CSS class, even if you name itdark-mode
– Mister Jojo Commented Feb 14 at 22:04