If you ever used Google’s iGoogle feature, you may have noticed that depending on the hour, the background changes. Using JavaScript we can create the same feature, which will rotate an image based on the time that the the user visits.
Here are the three images that we are going to be using.

<script language="JavaScript" type="text/javascript">
var now = new Date();
var hour = now.getHours();
if (hour=11){
var TimeofDay = "IMG src="images/morning.jpg""
}else if(hour > 11 hour = 17){
var TimeofDay = "IMG src="images/afternoon.jpg""
}else if(hour > 17){
var TimeofDay = "IMG src="images/night.jpg""
}
</script>
The first thing we need to do in our script is to find what hour it currently is. We used the Date() function to do this. This is nothing that we have not seen already in earlier tutorials. We are then going to use two functions to determine what image to display. In our script we will have any time before 11 to display a sunrise, any time between 12 to 17 to display the afternoon image, and any time greater then 17 to show our night sky image. Later in the body, when we want to display the image we use the document.write, and pass the TimeofDay to it.
Sometimes we do not want to stuff every code into our page, i personaly like to keep everything seperate and just call them in.
Create a new file and call it what ever you like in this example i will call it ( timeOftheDayImage.js )
1. Put the above code into this file and save it. Make sure to get rid of the opening and closing script tags.
2. To embed (timeOftheDayImage.js) into your Web page where you like to show.
Use these tags in your Web page.
<SCRIPT LANGUAGE="JavaScript" SRC="timeOftheDayImage.js"> </SCRIPT>
Note: Do not forget to change the path to the file above,
if you put the timeOftheDayImage.js file inside of another directory.
I normaly put all my javascript files inside a directory called ( js )
if thats the case then your path from your webpage should be like this ( js/timeOftheDayImage.js )


























One Comment
Thank you to all our readers. Here is another great tutorial for your next project.