Displaying a different image depending on the time of the day

With the above knowledge, and a little HTML, you can display different images according to the date/time. Here is a common example: Displaying a different image depending on whether it is mourning or night.

Lets first get two images: (One for mourning, one for night.)

day.gif (11196 bytes) night.gif (6906 bytes)
var current= new Date()
var day_night=current.getHours()
if (day_night<=12)
	document.write("<img src='day.gif'>")
	document.write("<img src='night.gif'>")


There is one very important concept here:

  • Take a look at the two lines highlighted. What we have done here is dynamically written out the html code required to display an image (not to be mistaken with dynamic html). Here is where JavaScript becomes amazing. You don't have to hard code your html tags into your webpage- allow JavaScript to think and write it out for you. Notice that we used the "write" method to do so, with the html code enclosed in " " This is how we write html in JavaScript.
  • So basically, if its mourning (before noon), "day.gif" will be shown, and at night, "night.gif."
  • Don't you get mesmerized looking at that sunset picture?

What else can you do with this object? Plenty. How about a live clock? Well, that is really fairly easy to do, provided we know this very important function: setTimeout().