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)
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() {});
}
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");
});
});
});
<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>
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");
});
}