I have written a script using JavaScript that allows me to detect the user's preferred color mode and switch between light and dark mode using a button. But the whole thing has to be adjusted for each page.
Is there a simpler solution to both detect the preferred color mode and switch between the two modes using a switch (button)? Since CSS already has the prefers-color-scheme feature, I would only need to know how to switch between light and dark mode via a button as a user.
Here's my current code, written in plain JS:
window.onload = detectTheme()
function detectTheme() {
// This detects the device color mode when the user enters the webpage
var theme = document.getElementById("theme");
// Get the ID from the link we want to change
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme.href = '/link/to/darkmode/file'
// Changing the file based on the color mode ("dark" file for dark-mode)
}
else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
theme.href = '/link/to/lightmode/file'
// Changing the file based on the color mode ("light" file for light-mode)
}
}
var switchLD = document.getElementById("switch");
// This is the ID from the switch button
switchLD.onclick = function toggleTheme() {
var theme = document.getElementById("theme");
// Checks what color-mode file is used
if (theme.getAttribute('href') == '/link/to/lightmode/file') {
theme.href = '/link/to/darkmode/file'
// Changing the file from light to darkmode
}
else if (theme.getAttribute('href') == '/link/to/darkmode/file') {
theme.href = '/link/to/lightmode/file'
// Changing the file from dark to lightmode
}
}
Any answer would help me a lot. If there is a solution using only CSS (or SCSS / SASS), I'd love to use it.