Development

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).

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('');//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

 

Full code is:

 

 

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago