How to trigger a dark theme at night
I recently added some JavaScript to auto-trigger a dark theme on this site at night. The strategy is simple: find the user’s current hour, and then place a dark
class on the <html>
element if it’s late at night. This is the bare minimum JavaScript necessary to do this:
var hour = new Date().getHours()
var isNight = hour < 6 || hour > 21
if (isNight) {
var html = document.getElementsByTagName('html')[0]
html.classList.add('dark')
}
Then, you can make your CSS respond appropriately:
/* Make the page dark */
html.dark {
background: #000;
color: #fff;
}
/* Adjust elements inside the page if needed */
.dark .element {
background: #0a0a0a;
}
For best results, make sure that your dark CSS comes at the end of your normal CSS (so it takes precedence); otherwise, you might need lots of !important
overrides.
You can also let your users toggle the theme themselves. After adding your CSS, just create a button that runs this function:
function toggleDarkTheme() {
var html = document.getElementsByTagName('html')[0]
html.classList.toggle('dark')
}
And that’s that! Happy coding.