Displaying An Image On A Web Page Based Upon The Current Time With JavaScript / DOM

Recently asked on Yahoo! Answers:

Picture on a schedule?

How do I run a photo based on a schedule on my website?? I’m using Microsoft Frontpage. I know HTML, but no other programming languages. HELP PLEASE?

This is fairly straightforward, provided we know what kind of schedule we want to use. Since the questioner didn’t give a specific schedule he wants to be on, I’ll provide three examples:

  • The current hour, from 12 a.m. (midnight) to 11 p.m.;
  • The current day, from Sunday through Saturday;
  • The current part of the day: Early morning, morning, afternoon, evening.

We also want to make sure we’ve done the following:

  • Resized all the images to be a common size; this will lessen the design issues we face.
  • Placed all the images we want to use in the same directory.
  • Written down all the names of the images we will use.

To begin, we need to add an IMG tag to our Web page, wherever we want the “random” image to appear. It need only contain an ID attribute, which we will call myimage; no need for a src, alt or other attributes, as we’ll assign those later via JavaScript.

We also need to add an onload attribute to the page’s BODY tag, which will call the JavaScript function we make; we’ll name that function showRandomImage().



With the HTML prepared, we can go ahead and write the showRandomImage() JavaScript, which is really pretty straightforward.

We begin with two variables: theImage and thePath. theImage will be a reference to the IMG tag we placed in the HTML, which we will get using getElementById(); thePath is the HTTP path to the images folder we will use, relative to the page we are working on.

A quick aside on HTTP path and relative addressing: When I say “HTTP path”, I mean the URL you will use. It’s not the same as the “physical path,” which is the location of the file on the Web server’s hard drive.

For example, this Web site’s base HTTP path is http://www.dougv.com/. In there, I have a subdirectory named demo, plus another subdirectory named js_random_image_time, which holds the demo Web pages, and within that, another subdirectory named images, which hold the images for the demo pages (links at bottom of article).

Therefore, the HTTP path to the images, relative to the demo pages, is images/. The images directory I want is one level down from the pages I am using them in.

function showRandomImage() {
	var theImage = document.getElementById('myimage');
	var thePath = 'images/';

What we do next depends on what kind of time increment we want to use for our schedule. I’ll start with Example 1, which shows a different image every hour, and then the other two examples.

Example 1: Hour Of Day

To show a different image each hour, we need to have at least as many images as there are hours in the day: That is, 24 pictures.

So that our script knows which image to show at which hour, we’ll store all the possible images in an array, and explicitly write out which images belong to which hour. (We could have used a different method than this, such as renaming all the images after an hour of the day — 1.jpg for 1 a.m., 12.jpg for noon, 18.jpg for 6 p.m., etc. — but this system provides maximum flexibility for existing Web sites.

var thePictures = new Array();
thePictures[0] = 'allison_krieger_miss_florida.jpg';
thePictures[1] = 'amber_bennett_miss_arkansas.jpg';
thePictures[2] = 'angela_corsi_miss_michigan.jpg';
thePictures[3] = 'annette_olson_miss_north_dakota.jpg';
thePictures[4] = 'blair_pancake_miss_tennessee.jpg ';
thePictures[5] = 'callee_bauman_miss_south_dakota.jpg';
thePictures[6] = 'donilee_mcginnis_miss_oregon.jpg';
thePictures[7] = 'emily_hughes_miss_new_hampshire.jpg';
thePictures[8] = 'emily_nicholas_miss_iowa.jpg';
thePictures[9] = 'georgine_dimaria_miss_new_jersey.jpg';
thePictures[10] = 'heidi_voight_miss_connecticut.jpg';
thePictures[11] = 'jacquelynne_fontaine_miss_california.jpg';
thePictures[12] = 'jamie_wilson_miss_louisiana.jpg';
thePictures[13] = 'karissa_staples_miss_maine.jpg';
thePictures[14] = 'kate_michael_miss_dc.jpg';
thePictures[15] = 'katherine_crouch_miss_idaho.jpg';
thePictures[16] = 'kristen_eddings_miss_washington.jpg';
thePictures[17] = 'meghan_coffey_miss_wisconsin.jpg';
thePictures[18] = 'michaela_gagne_miss_massachusetts.jpg';
thePictures[19] = 'miss_oklahoma_lauren_nelson.jpg';
thePictures[20] = 'nicole_swanson_miss_minnesota.jpg';
thePictures[21] = 'sarah_french_miss_missouri.jpg';
thePictures[22] = 'sarah_watson_miss_vermont.jpg';
thePictures[23] = 'shelley_benthall_miss_south_carolina.jpg';

Note that our array begins its index at 0, not 1. That’s fine, because JavaScript’s Date() function displays the hours of the day as military time (from 0 to 23, where 0 is midnight and 23, 11 p.m.), so the two will match up just fine.

With all the images listed out, we get the current time, and then get the current hour from that time:

var theTime = new Date();
var theHour = theTime.getHours();

Another quick aside on JavaScript’s Date() class: The time you get in JavaScript is the time used by the user’s computer, not the time of your Web server. For example, if your Web server is in New York City, your visitor is in London, and it is 1 p.m. EST in New York, your visitor’s computer probably believes it is 6 p.m., so that is the time it will use.

You can correct for this problem, to some degree, by using Greenwich Mean Time instead of the local time. That still requires the user’s computer to have a somewhat accurate date and time, and to be using the correct time zone, but will provide more uniformity.

W3Schools.com has an excellent reference if you want to learn more about the JavaScript Date() object.

Now that we know what hour of the day it is, we can get the source for our IMG tag, by concatenating the path of the image directory and the corresponding picture array entry we set earlier. For example, if it’s 3 p.m., we simply need to get the 14th item in the array, and add that to the image directory path.

var imagePath = thePath + thePictures[theHour];

We assign this path to the image, and then assign the image’s alt and title attributes to be the name of the image we’re showing. (Internet Explorer uses the alt tag to show the photo’s name as a tool tip on mouseover; Mozilla uses the title attribute to do the same.)

theImage.src = imagePath;
theImage.alt = thePictures[theHour];
theImage.title = thePictures[theHour];

Believe it or not, it’s that simple.

Example 2: By Day Of Week

Changing the script to use a different time part is also pretty easy. All we need to do is change the array so it has as many elements as we’ll need, and then change the method we use on the Date() class to get the information we want.

For example, the getDay() method in JavaScript will give us a number from 0 (Sunday) to 6 (Saturday), representing the day of the week. We therefore need at least seven images to put into our array, which again begins at 0 and ends at 6, just like the result we get from getDay().

Otherwise, the script is exactly the same as above.

function showRandomImage() {
	var theImage = document.getElementById('myimage');
	var thePath = 'images/';

	var thePictures = new Array();
	thePictures[0] = 'allison_krieger_miss_florida.jpg';
	thePictures[1] = 'blair_pancake_miss_tennessee.jpg';
	thePictures[2] = 'donilee_mcginnis_miss_oregon.jpg';
	thePictures[3] = 'heidi_voight_miss_connecticut.jpg';
	thePictures[4] = 'meghan_coffey_miss_wisconsin.jpg';
	thePictures[5] = 'kate_michael_miss_dc.jpg';
	thePictures[6] = 'kristen_eddings_miss_washington.jpg';

	var theTime = new Date();
	var theWeekday = theTime.getDay();

	var imagePath = thePath + thePictures[theWeekday];

	theImage.src = imagePath;
	theImage.alt = thePictures[theWeekday];
	theImage.title = thePictures[theWeekday];
}

Example 3: By Part Of Day

If we really want to be clever, we can do some math, altering the information we get from one of the Date() methods to determine what we show.

For example, the day has four parts: Early morning (midnight-6 a.m.), morning (6 a.m. – noon), afternoon (noon-6 p.m.) and evening (6 p.m. – midnight).

We can get the current part of the day by finding out what hour it is, then divide that number by 6. We round the result down to the nearest whole integer, and that gives us something between 0 and 3 — or, simply, the part of the day, again beginning, just like our array, at 0.

And once again, we replace the relevant parts of our script with the changes needed specify which images we will show, and to select one of those images in the array.

function showRandomImage() {
	var theImage = document.getElementById('myimage');
	var thePath = 'images/';

	var thePictures = new Array();
	thePictures[0] = 'allison_krieger_miss_florida.jpg';
	thePictures[1] = 'blair_pancake_miss_tennessee.jpg';
	thePictures[2] = 'miss_oklahoma_lauren_nelson.jpg';
	thePictures[3] = 'shelley_benthall_miss_south_carolina.jpg';

	var theTime = new Date();
	var theHour = theTime.getHours();

	theHour /= 6;
	theHour = Math.floor(theHour);

	var imagePath = thePath + thePictures[theHour];

	theImage.src = imagePath;
	theImage.alt = thePictures[theHour];
	theImage.title = thePictures[theHour];
}

That’s all there is to it. With a little bit of tinkering, you can make this basic script work however you want.

A final aside on a default image: You’ll notice that my code does not trap for persons who may not be using JavaScript: That is, if you don’t have, or enable, JavaScript, and you look at these demo pages (again, linked below), you won’t see an image displayed at all.

You may, therefore, want to specify a default image by assigning src and alt attributes to the IMG tag itself. I didn’t do that because some visitors find it disconcerting to have page elements, such as images, change unexpectedly; if you use a default image tag, that will show up, then be replaced by the proper image.

It’s a matter of personal choice. My feeling is that I seldom write Web pages targeted for text-only readers and if a visitor turns off JavaScript, that’s his problem for being paranoid. I’ll design to the vast majority of people, who use graphics-enabled browsers and don’t like it when things happen that they weren’t expecting.

Demos And Downloads

You can see working demos of these scripts here:

Example 1: By Hour Of Day

Example 2: By Day Of Week

Example 3: By Part Of Day

You can download this code and the images from here:

Displaying An Image On A Web Page Based Upon The Current Time With JavaScript / DOM Demo Code

I distribute code under the GNU GPL version 3.

Related Posts
  1. Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript (51.5)
  2. Display A Random Image With JavaScript / DOM (33.1)
  3. Changing CSS Styles Via JavaScript, Based On The User's Web Browser (24)
  4. Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP (19.3)
  5. Dynamically Populating A Listbox From A Textbox Via JavaScript / DOM (16.9)

The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.

4 Comments

  1. abdul says:

    pretty sweet. i must say you explained it very clearly. I’d learnt java a few years back, but didn’t realise something like this could be done using java. thanks!

  2. [...] clocks on Web pages are very popular; my quickie demo site uses one. And as I’ve discussed in previous entries, the problem — as this questioner notes — is that you never know what time a user’s computer may [...]

  3. [...] question is startlingly similar to the question I answered for displaying an image based on a schedule; in fact, we’ll use a similar approach here. But what this allows us to do is discuss how to use [...]

  4. [...] question should sound somewhat familiar to readers of this blog: We’ve dealt with displaying images based on the current time, randomly displaying an image, displaying an image based on user input and, earlier today, loading [...]