'Change image on home page according to time of day with CSS?

I am attempting to create the following:

I have five svg´s, each of them representing a different time in the day. Morning, Midday, Afternoon, etc.

Is it possible to make the image change depending of what time it is at the users location? If yes, is this possible with CSS only? (I am only familiar with HTML and CSS so far). If not, what would be the easiest way to achieve it in general?

All posts or threads I have found so far used other languages.

Edit: enter image description here

TIA



Solution 1:[1]

You have some things incorrect on the code you wrote in the comment, you dont need to use innerHTML, just use document.getElementById("img").src instead of that.

One good tip using JavaScript, is to put it on a function, and call to that function when page is loaded. If you use cpoy this code, it should work correctly:

window.onload = changeImage;

function changeImage() {
    const time = new Date().getHours();

    if (time < 6) {
        document.getElementById("img").src = "img/meerkat_five.svg";
    } else if (time < 9) {
        document.getElementById("img").src = "img/meerkat_one.svg";
    } else if (time < 14) {
        document.getElementById("img").src = "img/meerkat_two.svg";
    } else if (time < 17) {
        document.getElementById("img").src = "img/meerkat_three.svg";
    } else if (time < 20) {
        document.getElementById("img").src = "img/meerkat_four.svg";
    }
}

I hope this works for you.

Solution 2:[2]

You can use JavaScript for making this, you can create a new file .js, or just add JavaScript in your html, between <script> tags.

You should take the hour its actually, using this function:

<script type=»text/javascript»>

var date = new Date();
var hour = (date.getHours());

</script>

Then you just can compare the hour you get with the time you want, and change the image:

<script type=»text/javascript»>

var date = new Date();
var hour = (date.getHours());

if (hour > 12) {
     document.getElementById("img").src="img/day.png";
}

</script>

In your html, you must have a

<img id="img" src="img/picture.png"> 

You just will need to change the if statements, and put the hours you prefer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 marc_s