DEV Community

Lens
Lens

Posted on

How to make a dark mode toggle with CSS and Javascript

Having a dark mode on your website is a great thing that many web developers use. It's also really easy to make with one CSS class and a javascript EventListener.

Making the CSS class

The first thing you need to make is a css class that has the dark mode. This is usually the body, but you can also put this for other specific elements that you want the dark mode on. In the class you it should background-color set to a dark color. It should also have the text set to be brighter so it can be easier for the user to see when it's dark.

.dark {
  color: #ffff;
  background-color: #0d1b2a;
}
Enter fullscreen mode Exit fullscreen mode

The Javascript function

Now we give a button an EventListener with a function for whenever it's clicked. Inside the function it'll have the DomTokenList method classList.toggle and inside it we add the CSS class with the dark theme. Now whenever we click the button it toggles the dark theme on or off.

darkMode.addEventListener('click', function () {
    document.body.classList.toggle('dark');
  });
Enter fullscreen mode Exit fullscreen mode

As an example heres this quick codepen i made, if you click the moon over at the top it'll change the theme! (Sorry it looks bad, i had a fever this week so i didn't feel like doing a lot)

Top comments (2)

Collapse
 
emmancodex profile image
emmancodex

its not working in ...

im so fustrated right now😢`

button.addEventListener(click,
function () {
return document.body.classList.toggle(".darktheme");
});
`

`
`

Collapse
 
lensco825 profile image
Lens

@emmancodex I don't think you need the return keyword in your function since it only returns values like a string, number, or variable. Also you don't need the period on your class name because you just need the name and not the CSS selector. So it should be like this:

button.addEventListener('click', function () {
    document.body.classList.toggle("darkTheme");
  });
Enter fullscreen mode Exit fullscreen mode