Change background and text based on time with Javascript

Changing a websites background color based on client side (viewers) time is easily done with a small amount of vanilla Javascript.

Changing a website background color or other styles has its uses such as displaying a night mode theme or setting a mode to the users/viewers time.

The only HTML needed is the text to display the time and name for the time (morning, day, evening or night).

<h1 id='time'></h1>

Next get the viewers date/time and then format it to only have the hour in 24 hour format

var now = new Date();
var hours = now.getHours();

Build the time string (11:41 AM etc)

var ft = now.toLocaleString("en-US", {
        hour: "numeric",
        minute: "numeric",
        hour12: true
});

Then run if statements to find what style and describer word to use for the given time

if (5 <= hours && hours < 8) {//Morning
        document.write('<body style="background: #F3904F; background: -webkit-linear-gradient(to right, #3B4371, #F3904F); background: linear-gradient(to right, #3B4371, #F3904F); color: white">');//Gradient styled background with white text
        var type = "Morning";//Time describer word
}

Lastly setting the inner HTML of the id ‘time’

document.getElementById("time").innerHTML = `The time is ${ft} it is ${type}`;//The time is 5:18 PM it is Evening

 

js background change with time

Full code is:

<h1 id='time'></h1>
<script>
    var now = new Date();
    var hours = now.getHours();
    var ft = now.toLocaleString("en-US", {
        hour: "numeric",
        minute: "numeric",
        hour12: true
    });
    if (5 <= hours && hours < 8) {//Morning
        document.write('<body style="background: #F3904F; background: -webkit-linear-gradient(to right, #3B4371, #F3904F); background: linear-gradient(to right, #3B4371, #F3904F); color: white">');
        var type = "Morning";
    }
    if (8 <= hours && hours < 17) {//Day
        document.write('<body style="background: #00B4DB; background: -webkit-linear-gradient(to right, #0083B0, #00B4DB); background: linear-gradient(to right, #0083B0, #00B4DB); color: white">');
        var type = "Daytime";
    }
    if (17 <= hours && hours < 19) {//Evening
        document.write('<body style="background: #355C7D; background: -webkit-linear-gradient(to right, #C06C84, #6C5B7B, #355C7D); background: linear-gradient(to right, #C06C84, #6C5B7B, #355C7D);\n color: white">');
        var type = "Evening";
    }
    if (19 <= hours && hours < 5) {//Night
        document.write('<body style="background: #0f2027; background: -webkit-linear-gradient(to right, #0f2027, #203a43, #2c5364);  background: linear-gradient(to right, #0f2027, #203a43, #2c5364); color : white">');
        var type = "Nighttime";
    }
    document.getElementById("time").innerHTML = `The time is ${ft} it is ${type}`;
    //CSS gradient backgrounds from https://uigradients.com
</script>