Search code examples
csssvgsvg-animate

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

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