I’m adding dark and light theme, I changed bg-color, but can’t change text color
Css (I don’t have variables)
JavaScript
x
7
1
body {
2
color: var(--text-color, white);
3
background-color: var(--background, #181818);
4
margin: 0px;
5
padding: 0px;
6
}
7
Js
JavaScript
1
15
15
1
document.getElementById('dark_theme').addEventListener
2
('click', () => {
3
document.documentElement.style.setProperty
4
('--background', '#181818');
5
('--text-color', 'white')
6
7
})
8
document.getElementById('light_theme').addEventListener
9
('click', () => {
10
document.documentElement.style.setProperty
11
('--background', 'white');
12
('--text-color', 'black')
13
14
})
15
Advertisement
Answer
If I were you I’d have added a class to the body element such as “.darkTheme” and that’d be only one line of JS and a faster program. The snippet below shows you how to do it, just a point that you can have the body inherit a theme (class) by default.
JavaScript
1
8
1
document.getElementById('dark_theme').addEventListener('click', () => {
2
document.body.classList.add("darkTheme");
3
document.body.classList.remove("lightTheme");
4
});
5
document.getElementById('light_theme').addEventListener('click', () => {
6
document.body.classList.remove("darkTheme");
7
document.body.classList.add("lightTheme");
8
});
JavaScript
1
16
16
1
body {
2
color: var(--text-color, white);
3
background-color: var(--background, #181818);
4
margin: 0px;
5
padding: 0px;
6
}
7
8
body.darkTheme {
9
--background: #181818;
10
--text-color: white;
11
}
12
13
body.lightTheme {
14
--background: white;
15
--text-color: black;
16
}
JavaScript
1
8
1
<html>
2
3
<body>
4
<button id="dark_theme"> Apply the dark theme </button>
5
<button id="light_theme"> Apply the light theme </button>
6
</body>
7
8
</html>
Although if you don’t seek this way, I can help you with your own.
The point is your JS code ends the setProperty method with “);” and you can’t expect your code to work as “(‘–text-color’, ‘white’)” makes no sense.
You can edit your JS like this:
JavaScript
1
10
10
1
let myDocStyle = document.documentElement.style;
2
document.getElementById('dark_theme').addEventListener('click', () => {
3
myDocStyle.setProperty('--background', '#181818');
4
myDocStyle.setProperty('--text-color', 'white');
5
});
6
document.getElementById('light_theme').addEventListener('click', () => {
7
myDocStyle.setProperty('--background', 'white');
8
myDocStyle.setProperty('--text-color', 'black');
9
});
10