Detect OS theme and apply Dark Mode
Good morning I would like to know if it is possible to detect the user's operating system theme and automatically apply (if applicable) the metronic dark theme.
I say this to avoid putting together both metronic css styles and use:
@media (prefers-color-scheme: dark)
Replies (2)
Edit:
I tried this and it works, but it interferes with my button code to switch to dark mode manually.
Javascript code to detect OS theme:
let darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (darkMode) {
KTApp.setThemeMode("dark", function() {});
} else {
KTApp.setThemeMode("light", function() {});
}
Javascript code of the button:
KTUtil.onDOMContentLoaded(function() {
var darkModeToggle = document.querySelector('#theme_mode_dark');
var lightModeToggle = document.querySelector('#theme_mode_light');
darkModeToggle.addEventListener('click', function() {
KTApp.setThemeMode("dark", function() {
darkModeToggle.classList.add('d-none');
lightModeToggle.classList.remove('d-none');
});
});
lightModeToggle.addEventListener('click', function() {
KTApp.setThemeMode("light", function() {
darkModeToggle.classList.remove('d-none');
lightModeToggle.classList.add('d-none');
});
});
});
HTML code of the button:
<div class="d-flex align-items-center ms-1 ms-lg-3">
<button class="btn btn-icon btn-icon-muted btn-active-light btn-active-color-primary w-30px h-30px w-md-40px h-md-40px" >
<i class="fonticon-sun fs-2"></i>
</button>
<button class="btn btn-icon btn-icon-muted btn-active-light btn-active-color-primary w-30px h-30px w-md-40px h-md-40px d-none" >
<i class="fonticon-moon fs-2"></i>
</button>
</div>
I placed the code to detect the OS theme and my manual button javascript code (The separate codes) and as I said, it works, but:
-If it is placed in Dark mode automatically and the manual button is tapped to change it to Light, the button does not work.
Thank you in advance.
Hi,
Detecting the system mode is possible only via Javascript and using the page loading indication you can implement javascript code that detects the system mode and stores in it Cookie to pass to your server-side next pages will be loaded with dark mode CSS generated in the server side.
The toggle issue can be solved by properly showing/hiding the toggle buttons when you detect the system mode:
let darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (darkMode) {
KTApp.setThemeMode("dark", function() {
darkModeToggle.classList.add('d-none');
lightModeToggle.classList.remove('d-none');
});
} else {
KTApp.setThemeMode("light", function() {
darkModeToggle.classList.remove('d-none');
lightModeToggle.classList.add('d-none');
});
}
Regards.