My code, shown below, for a dark theme toggle button isn’t working; Visual Studio Code isn’t telling me I have any errors. Can someone help me figure out what the issue is?
document.getElementById('themeButton').addEventListener('click'),
function() { /* Theme button script */
document.body.classList.toggle('dark-theme');
}
body {
background-color: rgb(246, 246, 246);
color: black;
h1 {
color: rgb(63, 66, 145);
/* Header 1 features */
font-size: 50px;
padding-bottom: 8px;
margin: 10px;
}
h2 {
font-family: Arial, Helvetica, sans-serif;
/* Header 2 features */
margin: 10px;
}
p {
font-family: Arial, Helvetica, sans-serif;
/* Paragraph features */
font-size: 20px;
padding-bottom: 10px;
margin: 10px;
}
/* Dark theme styles */
.dark-theme {
background-color: #A9a9a9;
/* Dark gray background */
color: #F5F5F5/* Light gray body text */
}
.dark-theme h1 {
color: rgb(170, 172, 244)/* Light blue text for header 1 */
}
}
<h1>Basic Website</h1>
<!-- Site text content -->
<hr>
<h2>Welcome to my basic webpage.</h2>
<p>This isn't my first time coding, but it's been so long that it might as well be.</p>
<img src="treehouse.jpg" alt="An elaborate treehouse.">
<!-- Image -->
<hr>
<button id="themeButton">Change Theme Color</button>
<!-- Theme button -->
The button should change the background to a dark gray, and the text should become light gray, but the button changes nothing when clicked.
2
Answers
You have an error here
You must pass the function as the second argument to
addEventListener
, like thisYou also have to move your
.dark-theme
CSS rules outside of body, because if you use it like in your example, it can only affect body’s children, not body itself.(Two examples ahead!)
You need to reference the self
body
using&
in Nested CSS since you actually toggle that class on thebody
element usingdocument.body.classList.toggle('dark-theme');
Then, for the
H1
you can use: H1 being descendant of dark theme body class like:and same as above
h1
styles you can style any other selector.Also, your JS had a typo; all fixed in the following example:
I frankly would not bother creating any buttons to toggle anything. Less UI the better, and it’s 2024. and dark themes are pretty common in UI design. Instead, I would focus on the User’s desired OS preferred theme using the @media prefers-color-scheme and some CSS properties: