'.netCore 3.0 Dark theme text color is not applied correctly
I am attempting to update my site to use a dark mode. The functionality seems to work, but only part of it. The Text-color is not updating until I toggle it on the chrome console, same with Microsoft edge. Not sure why. I have applied the !important tag in the CSS file, but that doesn't change the outcome.
This is an MVC app using .netCore 3.0, I do not know what I am doing as I only really do backend development.
The expected results should be that the text correctly applies with the toggle. Currently, does not apply until I toggle in debug console. All other color changes do apply. I have the following in my css file
[data-theme="dark"] {
--primary-color: #9A97F3;
--secondary-color: #818cab;
--font-color: #e1e1ff !important;
--bg-color: #161625;
--heading-color: #818cab;
}
with the following logic to apply the change
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
}
else {
document.documentElement.setAttribute('data-theme', 'light');
}
}
toggleSwitch.addEventListener('change', switchTheme, false);
function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'dark'); //add this
}
else {
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('theme', 'light'); //add this
}
}
const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
if (currentTheme === 'dark') {
toggleSwitch.checked = true;
}
}
-edit, fixed code format
Solution 1:[1]
Here is a working demo to change theme with buttons:
css:
<style>
.dark-mode {
background-color: black;
color: white;
}
.light-mode {
background-color: white;
color: black;
}
</style>
Html:
<h3>Test</h3>
<button onclick="darkMode()">Darkmode</button>
<button onclick="lightMode()">LightMode</button>
js:
function darkMode() {
var element = document.body;
element.className = "dark-mode";
}
function lightMode() {
var element = document.body;
element.className = "light-mode";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yiyi You |

