Skip to content

Instantly share code, notes, and snippets.

const button = document.querySelector(".color-switch");
button.addEventListener("click", function() {
const body = document.querySelector("body");
body.classList.toggle("lightmode");
body.classList.toggle("darkmode");
if (button) {
button.innerText = body.classList.contains("lightmode") ? "Dark" : "Light";
}
const button: HTMLButtonElement = document.querySelector(".color-switch");
button.addEventListener("click", function() {
const body: HTMLBodyElement = document.querySelector("body");
body.classList.toggle("lightmode");
body.classList.toggle("darkmode");
if (button) {
button.innerText = body.classList.contains("lightmode") ? "Dark" : "Light";
}
<body class="darkmode">
<header>
<button class="color-switch">Light</button>
</header>
<h1>CSS Variable Dark Mode Switcher</h1>
</body>
body {
font-size: 1.2rem;
background: var(-background-fallback);
background: var(-background-gradient-webkit);
background: var(-background-gradient);
color: var(-text);
}
a {
color: var(-links-dark);
}
.darkmode {
--text: #fff;
--links: #66e387;
--bg-start: #2c5364;
--bg-middle: #203a43;
--bg-end: #0f2027;
--background-fallback: #0f2027; /* fallback for old browsers */
--background-gradient-webkit: -webkit-linear-gradient(
to bottom,
var(--bg-start),
document.querySelector('.wrapper').style.setProperty("--textcolor","pink");
document.documentElement.style.setProperty("--textcolor","pink");
.wrapper {
--textcolor: #66e387;
}
:root {
--textcolor: #ffc845;
}
:root {
--textcolor: #ffc845;
}
div {
color: var(--textcolor);
}
.wrapper {
--textcolor: #66e387;
}