How to Add Night Mode to Your WordPress Site with JavaScript & CSS

May 6, 2019

Lately, I’ve been thinking a lot readability and information retention. I firmly believe that people have an easier time comprehending dark text on a light background. However, there are certainly times when light text on a dark background is a valid design choice. For example, staring at a white background when reading late at night is terrible for your eyes.

To address this issue, I added a “night mode” to my website that automatically turns on after 5 PM and stays active until 5 AM. I decided to forgo the typical night/light mode button because there’s nowhere obvious to put such a button on my website. Here’s how I added the automatic night mode feature.

Automatic night mode on BrianLi.com.

I added the JavaScript snippet below right after <body>.

<script defer type = "text/javascript" >
now = new Date();
hour = now.getHours();
if (hour >= 5 && hour <= 16) {
document.querySelector('body').classList.add('light') }
</script>

This JavaScript snippet does two things.

  • Assign the current hour of the day to hour.
  • Add a light CSS class to the HTML document if hour is between 5 (5 AM) and 16 (4 PM).

Next, I added some CSS to my stylesheet to style all the elements that needed a color change for light mode. I did it this way because my website was designed with a dark background. If your website has a light background, you’ll probably want to add a dark class with the JavaScript snippet instead.

body {
  background: #1f2021;
}

body.light {
  background: #fafafa;
}

That’s it! Now, my WordPress site renders in light mode between 5 AM and 5 PM, and dark mode between 5 PM and 5 AM. Feel free to tweak the time ranges to suit your preference, and have fun!


Questions?

Find me on Twitter, or email me.