I recently implemented a dark mode feature on my WordPress site.
Here are the four modes I included:
1- Automatically based on user's system settings
2- Light mode
3- Semi-lit mode
4- Dark mode
The implementation is in place and functioning perfectly.
However, there is an issue with the code being inactive upon page load.
Currently, after loading the page, the code remains inactive. To activate it, users have to manually click on one of the mode options. I would like the code to be active regardless of the initial state of the page.
let bodyMode = document.querySelector("#pageMode");
let SystemMode = document.querySelector(".pageSystemMode");
let DarkMode = document.querySelector(".pageDarkMode");
let LightMode = document.querySelector(".pageLightMode");
let HalfLitMode = document.querySelector(".pageHalfLitMode");
SystemMode.addEventListener("click", function () {
const UserMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (UserMode) {
$(bodyMode).addClass("bodyDark");
$(bodyMode).removeClass("bodyLight bodyHalfLit");
} else {
$(bodyMode).removeClass("bodyLight bodyDark bodyHalfLit");
}
});
DarkMode.addEventListener("click", function () {
$(bodyMode).addClass("bodyDark");
$(bodyMode).removeClass("bodyHalfLit");
});
HalfLitMode.addEventListener("click", function () {
$(bodyMode).addClass("bodyHalfLit");
$(bodyMode).removeClass("bodyDark");
});
LightMode.addEventListener("click", function () {
$(bodyMode).addClass("bodyLight");
$(bodyMode).removeClass("bodyDark bodyHalfLit");
});
.main-selectMode {
position: absolute;
top: 20%;
left: 2%;
}
a.main-btn {
font-weight: 900;
padding: 10px;
direction: rtl;
color: #fff;
background: #2512b0;
border: none;
box-shadow: 0 0 4px #000, 0 0 4px #fff;
}
a.main-btn:hover,
.btn-secondary:hover,
.btn-check:checked+.btn,
.btn.active,
.btn.show,
.btn:first-child:active,
:not(.btn-check)+.btn:active {
color: #fff;
background: #2512b0;
border: none;
box-shadow: 0 0 4px #000, 0 0 4px #fff;
}
.main-btn::before {
margin: 0 7px 0 10px;
}
.main-btn::after {
...
</body>