My website has a JavaScript toggle that changes the color/theme of the page by adding/removing classes on the html
element. The default theme is white, the second theme is black (.dark-mode
), and the third theme is beige (.retro
).
The JavaScript code for the toggle has been simplified below:
const html = document.querySelector("html");
const button = document.querySelector(".contrast__link");
button.addEventListener("click", (e) => {
e.preventDefault();
if (html.classList.contains("dark-mode")) {
html.classList.remove("dark-mode");
html.classList.add("retro");
} else if (html.classList.contains("retro")) {
html.classList.remove("retro");
} else {
html.classList.add("dark-mode");
}
});
After the class/theme updates, I want to update the theme-color
in the document head
to match the new color scheme. Initially, it was set as:
<meta name="theme-color" content="#ffffff">
I attempted using CSS variables hoping it would dynamically change the color:
CSS
:root { --color-secondary : rgb(255,255,255); }
.dark-mode { --color-secondary : rgb(0,0,0); }
.retro { --color-secondary : rgb(243, 238, 226); }
Tag
<meta name="theme-color" content="var(--color-primary">
Unfortunately, it seems this method is not supported. Is there a way for the theme-color
to be inherited or does it have to be a fixed value?