Java Script Calendars for Your Website
By Stephen Bucaro
In this article, I'm going to show you how to use Java Script to create calendars
for your website. I'll explain the code in excruciating detail so that even if you are
not a programmer, you will understand it and feel comfortable using it and modifying it
for your own website. In order to follow this example, all you need is a basic idea of
how to use html code to create a table. You will also need a basic understanding of how
to use the Java Script document.Write statement.
I'll start by showing you how to code a basic calendar that shows the current month
with the current day highlighted. Then, I'll show you how to make your calendar a little
fancier, how to code a webpage that can display any month of any year or even several months
simultaneously, and finally, how to code a clickable calendar that will display appointments
you have for the day you clicked on.
The heart of the calendar code is a Java Script loop that draws an html table that
represents the calendar. Examine the basic structure of the code shown below below. As you
can see, this code creates a for loop within a for loop (nested for
loops). The inner loop writes a row of table cells - the days. The outer loop writes lines
of "inner loop" - the weeks.
for(row = 1; row <= rows; row ++)
for(col = 1; col < 8; col++)
As you can see, the code uses three variables; rows, col, and ndate. The line
document.write(ndate); writes the date. Replace that line with with the code shown below.
if(nloc < DayofWeek || ndate >= days[month])
The first line of this code introduces three more variables. DayofWeek contains the
cell number of the first day of the month. days[month] contains the number of days
in the month. I'll explain how those two variables are derived later. nloc keeps a count
of the table cells as they are drawn.
In plain Engish, this code reads:
If the table cell number is less than the cell number that the first day of the week
starts on, OR if the day number is higher than (or equal to) the number of days in the
month, write a blank cell. Otherwise (else) increment (add one) to the date and then write it
in the cell.
How does today's date get highlighted? Change the bottom part of the if statement
(the else) to that shown below.
if(ndate == day)
+ ndate + "</font>");
Today's actual date is stored in a variable named day. I'll explain how that is derived
later. The if statement above checks to see if the day number going into the table
cell (ndate) is equal to the day. If it is, it changes the font color to read. Otherwise,
the default font color (black) is used.