Categories
Professional

Ah, the power of JavaScript

I was asked about creating a javascript that would place an image on a page based on the day of the week. Easy enough right? Well, it took some tinkering, but here it is (http://www.servergoon.com/samples/dow/). For this demonstration I created eight images, each with the number 0 – 7. However, since the javascript Date Object returns 0 – 6, you will never see the 7.

The code for this is relatively simple, as you can see if you look at the source for this file. In the head I’ve preloaded the image, which, from what I can tell is necessary. Second I’ve got all of the files I want and named them the same, with the exception of the digit indicating the Day of the Week. Hence the DOW (stands for Day Of Week) for the name followed by a digit followed by .jpg. This is so I don’t have to write out 8 (or 31 if you were ambitious enough to do this for each Day Of the Month) individual lines (actually it would be more like 16 lines). It also makes the code to replace the image much easier and shorter to write as well.

The JavaScript in the head of the document looks like:

<SCRIPT language="JavaScript">
<!--
if (document.images)
{
	document.pics = new Array();
	for (j=0; j<8; j++) {
		document.pics[j] = new Image;
		var imageName = "DOW" + j + ".jpg";
		document.pics[j].src = imageName;
	}
}

//-->
</SCRIPT>

The code for the image is below, notice the ID tag, this is VERY important.  Notice that there is no source file, so no image is loaded by default

<img id="DayOfWeek" src="" height="50px" width="50px" border="1"/>
<img id="DayOfWeek2" src="" height="50px" width="50px" border="1"/>

And finally, the code to replace the images in the HTML code.

<script type="text/javascript">
   var myDate = new Date();
   var DOW = myDate.getDay();
   document.getElementById('DayOfWeek').src = document.pics[DOW].src;
   document.getElementById('DayOfWeek2').src = document.pics[DOW+1].src;
</script>

One more thing to note is that the JavaScript that changes the image needs to come AFTER the image in HTML code. If not, it doesn’t know about the image and can’t replace it. The other option would be to put the code in the head of the HTML file and trigger it with a function call.

I hope you found this useful, I know I can think of uses for this.  As always your mileage may vary.