Thanks to a very simple piece of JavaScript code, you can change the (background) colour of your website to reflect the time of day. Your website visitors will see a different version of your website: a dark mode during evening/nights, and a white/bright mode during the day.
Here are the steps to follow to have a simple dark mode for your personal website or blog! We will use a small snippet of JavaScript: so place your code instead <script></script> tags.
Get the visitor’s current time
Given your visitors may come from all over the world, you don’t want to use your server time. Visitors from the US and the UK may speak the same language, but they sure don’t have the same timezone. Instead, you want to capture the current time of your visitor via JavaScript and save it in a variable:
var today = new Date().getHours();
Each time the page is opened, the variable ‘today’ will be filled in with the visitor’s current time.
Define a time window when to show dark mode
Now it’s up to you to define a window between which you want to enable a night mode. Let’s say you want to show a darker version of your website between 8PM and 8AM. In JavaScript, we can translate this check as follows:
today >= 8 && today <= 20
As you may notice, 8PM is shown in ‘military style’. If you want 7PM, you should use 19 and so on.
Define a background colour with JavaScript
Now we know the visitor’s current time (wherever she or he lives), and we defined a time window. The last step is to add the necessary styling to the page. In my example, I want to make the background dark grey, and the text white (so that it remains readable for the user).
document.body.style.background = "#555";
document.body.style.color = "#fff";
The full JavaScript code
The full demo JavaScript code can be found below:
<!-- Night mode -->
<script>
var today = new Date().getHours();
if (today >= 8 && today <= 20) {
document.body.style.background = "#fff";
} else {
document.body.style.background = "#555";
document.body.style.color = "#fff";
}
</script>
You can add it to the bottom of the page and should work on virtually any website.