Making a time-sensitive dark theme
November 3, 2019
If you want to trigger a dark theme depending on the user's time, you can use JavaScript to find the user's current hour and place a dark
class on the <html>
element if it's late at night. This is the bare minimum code 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.