var Calendar = function () { this.year = (new Date).getFullYear(); this.dow = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; this.weekSpace = 2; // ratio of space between weeks to height of a day this.innerMargin = 110; // makeshift to adjust height for A5 }; Calendar.prototype.displayYearMonth = function () { var d = document.createElement('div'); d.textContent = this.year + '/' + this.month; d.className = 'year month'; this.container.appendChild(d); this.calcDays(); }; Calendar.prototype.displayDays = function () { var f = document.createDocumentFragment(); for (var i = 1; i <= this.days; i++) { var n = document.createElement('div'), y = this.getDayOfWeek(i), yb = this.dow[y]; n.textContent = i + ' ' + yb; n.className = 'days'; if (y === 0) n.className += ' endOfWeek'; if (i === 1) this.calcUnitHeight(y); n.style.height = this.daysHeight; if (1 < i && y === 1) n.style.marginTop = this.spaceHeight; f.appendChild(n); } this.container.appendChild(f); }; Calendar.prototype.getDayOfWeek = function (i) { var m = (this.month < 10 ? '0' : ''), day = (i < 10 ? '0' : '') + i; tmp = new Date(this.year + '-' + m + this.month + '-' + day); return tmp.getDay(); }; Calendar.prototype.calcDays = function () { var nextMonth = this.month % 12 + 1, nextMonthPre = nextMonth < 10 ? '0' : '', nextYear = this.year + Math.floor(this.month / 12), nextMonth1Day = new Date(nextYear + '-' + nextMonthPre + nextMonth + '-01'), tmpTime = nextMonth1Day.getTime() - 24 * 60 * 60 * 1000, tmpDate = new Date; tmpDate.setTime(tmpTime); this.days = tmpDate.getDate(); }; Calendar.prototype.calcUnitHeight = function (y) { var total = parseFloat(getComputedStyle(this.container).height), netHeight = total - this.innerMargin, numSpaces = Math.ceil((this.days - ((7 - y) % 7 + 1)) / 7), unit = netHeight / (this.days + numSpaces * this.weekSpace); this.daysHeight = unit + 'px'; this.spaceHeight = unit * this.weekSpace + 'px'; }; Calendar.prototype.setCalendars = function () { var cs = document.getElementsByTagName('c'); for (var i = 0, len = cs.length; i < len; i++) { var c = cs[i], y = c.getAttribute('year'), m = c.getAttribute('month'); if (m) { this.month = parseInt(m); } else { continue; } if (y) this.year = parseInt(y); this.container = c; this.displayYearMonth(); this.displayDays(); } }; var c = new Calendar(); c.setCalendars();