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().

<body onload="showRandomImage()">
<img id="myimage" />

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://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.


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


  1. 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. Hello that’s a very good article. But I have a different request. I would like to change the image at 12:00am every day. A pic of the day type of script. How can I do that? I don’t mind js, but php would be better in my situation.

    My images are in a folder currently, but I would like to store then urls in the mysql db if possible.

    Can you do something like that, or point me to a good example?

    1. @Brian: To achieve a “pic of the day,” you just change the script to have 31 images, and use theTime.getDate() to return a number from 1 to 31. Subtract 1 from that and you have a zero-based index:

      var theTime = new Date();
      var theDate = theTime.getDate() - 1;
      var imagePath = thePath + thePictures[theDate];

      Storing your photos in a MySQL database is another matter altogether.

      I believe it’s a mistake to do so because you are going to have to connect and query the DB for every visitor, even though this is effetively a static asset for 24 hours. That’s a lot of overhead for something that can live as a file. Just store them statically and let your page logic pick the right one.

      If for some reason it is easier to store the pictures in MySQL from a content management viewpoint, your alternative would be to cache the photo, using either a CDN (like the free CloudFlare option), file cache or memory cache, in order of preference. By caching, you can serve the right photo to everyone without having to make DB connections and queries for every request.

      If you have a highly customized page for each visitor that requires DB queries to build, then this concern is lessened; it’s just one more query in a series of queries.

      But in this day and age, a call to a RDBMS like MySQL for static page elements is a huge code smell. That’s the way we did things 20 years ago. It doesn’t work at today’s scale.

  3. Hi, Can this be used to display an image on say hour of day, day of month? IE 8:00-10:00 Monday 14th May 2018, 10:00 – 14:00 Monday 14th 2018 etc or would it be just hour day no date?

    Many Thanks

    1. @Gary: Sure. But there are up to 8,784 day-hours in a year (24 * 366), which means coding your source array would be pretty tedious.

      First, we need a means of getting the day of year, which we can do by prototyping some new methods onto the Date object. This is taken from Stack Overflow:

      Date.prototype.isLeapYear = function() {
          var year = this.getFullYear();
          if((year & 3) != 0) return false;
          return ((year % 100) != 0 || (year % 400) == 0);
      // Get Day of Year
      Date.prototype.getDOY = function() {
          var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
          var mn = this.getMonth();
          var dn = this.getDate();
          var dayOfYear = dayCount[mn] + dn;
          if(mn > 1 && this.isLeapYear()) dayOfYear++;
          return dayOfYear;

      And now that I have added these methods to the Date object, I can calculate the array position I should use:

      var theTime = new Date();
      var dayOfYear = theTime.getDOY();
      var theIndex = theTime.getHours();
      theIndex += (dayOfYear - 1) * 24;
      var imagePath = thePath + thePictures[theIndex];
  4. Hi, Apologies for the late reply, I think I was being slightly too ambitious there. I am basically looking to achieve a timetable covering a 24h period over 7 days. I will look back at the original thread as that would probably do.

    Thanks for the reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Check out the Commenting Guidelines before commenting, please!
  • Want to share code? Please put it into a GitHub Gist, CodePen or pastebin and link to that in your comment.
  • Just have a line or two of markup? Wrap them in an appropriate SyntaxHighlighter Evolved shortcode for your programming language, please!