I’m adding dark and light theme, I changed bg-color, but can’t change text color
Css (I don’t have variables)
body {
color: var(--text-color, white);
background-color: var(--background, #181818);
margin: 0px;
padding: 0px;
}
Js
document.getElementById('dark_theme').addEventListener
('click', () => {
document.documentElement.style.setProperty
('--background', '#181818');
('--text-color', 'white')
})
document.getElementById('light_theme').addEventListener
('click', () => {
document.documentElement.style.setProperty
('--background', 'white');
('--text-color', 'black')
})
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.
document.getElementById('dark_theme').addEventListener('click', () => {
document.body.classList.add("darkTheme");
document.body.classList.remove("lightTheme");
});
document.getElementById('light_theme').addEventListener('click', () => {
document.body.classList.remove("darkTheme");
document.body.classList.add("lightTheme");
});body {
color: var(--text-color, white);
background-color: var(--background, #181818);
margin: 0px;
padding: 0px;
}
body.darkTheme {
--background: #181818;
--text-color: white;
}
body.lightTheme {
--background: white;
--text-color: black;
}<html> <body> <button id="dark_theme"> Apply the dark theme </button> <button id="light_theme"> Apply the light theme </button> </body> </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:
let myDocStyle = document.documentElement.style;
document.getElementById('dark_theme').addEventListener('click', () => {
myDocStyle.setProperty('--background', '#181818');
myDocStyle.setProperty('--text-color', 'white');
});
document.getElementById('light_theme').addEventListener('click', () => {
myDocStyle.setProperty('--background', 'white');
myDocStyle.setProperty('--text-color', 'black');
});