Archive

Posts Tagged ‘HTML’

How To Create A Calendar Using An HTML Table And JavaScript

December 3rd, 2009 No comments

Assuming you’d need to create a calendar (or 2) in order to add in some text for specific dates, you’d probably want to create your own calendar using a simple HTML table and few lines of Javascript and later (depending on what additional text you want to display), you could add in some jQuery code to access the cells for the specific dates and modify their contents.

1
2
3
4
//Some constants
var monthLabels = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var daysOfWeek = new Array("Mon","Tue","Wed","Thu","Fri","Sat","Sun");
var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

The function below, takes the following parameters:
monthId = 1 or 2, month = 0 to 11, year = 2009 and above

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function constructCalendarTable(monthId,month,year)
{ var dateObj = new Date(); dateObj.setDate(1); dateObj.setMonth(month); dateObj.setYear(year);
  var dow_theFirstOfMonth = dateObj.getDay();
 
  //Get the maximum number of days in current month
  var maxDaysIntheMonth = daysInMonth[month];
  if(month == 1) { if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){ maxDaysIntheMonth = 29; } }
 
  //Creating the table
  var calmonthtd = $("#calmonth"+monthId+"td");
  var caltable = $("<table>").attr("align","center"); caltable.appendTo(calmonthtd);
 
  //Creating the label row
  var rowRMonthLabel = $("<tr>").attr("align","center"); rowRMonthLabel.appendTo(caltable);
  var rowRMonthLabelCell = $("<td>").attr("colspan","7").text(monthLabels[month]+", "+year);
  rowRMonthLabelCell.appendTo(rowRMonthLabel);
 
  //Creating the rest of the rows
  var rowR = $("<tr>"); rowR.appendTo(caltable);
 
  var dayOfMonthCounter = 0;
  for (var i=1;i<50;i++)
  { if(i%7==1) { rowR = $("<tr>"); rowR.appendTo(caltable); }
    var cellR = $("<td>").attr("id","calmonth"+monthId+"d"+i);
    if(i<=7) 
    { //Populating the days' headers
      cellR.addClass("calhdr").text(daysOfWeek[i-1]);
    }
    else 
    { //Populating the days
      var dayOfWeek = (i%7);
      if(dayOfWeek==dow_theFirstOfMonth && dayOfMonthCounter==0) {  dayOfMonthCounter=1; cellR.text(dayOfMonthCounter).addClass("calday"); }
      else if(i<=49 && dayOfMonthCounter>=1 && dayOfMonthCounter<maxDaysIntheMonth) { dayOfMonthCounter++; cellR.text(dayOfMonthCounter).addClass("calday"); }
      else
      cellR.text("").addClass("calnonday");
    }
    cellR.appendTo(rowR);
  }
}

[Update Dec 9, 2009]
I have used this code in one of my pet projects, http://cheapflightsearch.appspot.com/

Categories: Javascript Tags: , ,