by Jonathan Sexton
How I added dark mode to my website
Same website, two different color schemes
Last year I made it a point to redesign my website from scratch. I wanted something simple and minimalist looking that clearly stated what this was — a portfolio website.
After I rebuilt my website from the ground up it seemed like everywhere I turned there was another article about adding a dark mode to your website.
At first I didn’t think it would make that big of a difference because, while I am partial to darker colors, I felt like my website was a good balance between bright, fun colors and darker fonts.
I read some of the articles I mentioned earlier and the more I thought about it the more I decided to go for it.
I took some inspiration from Flavio Copes who wrote a terrific article on this very subject. Unlike what Flavio decided to do with his site, I didn’t add the user’s choice to local storage.
This is due, in part, to the differences between our sites. I have a static site and there are no redirects/separate pages aside from the blog which is on a different platform so users generally won’t be refreshing the page. It is a neat option and one that I may add in later on.
Ok, let’s dig into the nuts and bolts of how I accomplished my dark mode toggle.
The code to achieve this was fairly simple. I took the same approach as Flavio did and added the style changes through CSS. I had to take a few more steps because I have an image on my landing page.
I had to use the !important flag on some of the rules because they were not being applied properly. This was the easiest approach to implement and I know it’s not advised to use this flag so I’ll be looking for an alternative in the near future.
I start by selecting my
div with an id of
light-dark-mode-container and adding an event listener to it.
Next, I set my variables of
everything, which selects all content on the page, and
projectTiles because this class belongs to a particular set of overlays I do not want to have a background of a solid color.
Next, since I’m using
querySelectorAll which returns a static NodeList, I loop over all of the elements within both NodeLists and either toggle the class
dark or completely remove it from the elements returned by the variable
What I’m left with is a container at the top of my website with a toggle switch that allows the user to toggle between light and dark mode.
I hope you enjoyed this post and maybe you learned something too! If you decide to implement this on your own website or your next project please share it with me (leave me a comment or shout at me on Twitter). I’m always happy to see the work and projects that others create.
While you’re there why not sign up for my Newsletter? I promise I’ll never spam your inbox and your information will not be shared with anyone else.
Have an awesome day filled with love, joy, and coding!