Home > other >  Change image on home page according to time of day with CSS?
Change image on home page according to time of day with CSS?

Time:03-02

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

CodePudding user response:

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.

CodePudding user response:

You can use JavaScript for making this, you can create a new file .js, or just add JavaScript in your html, betwen 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 preffer.

  • Related