JSFiddle - React, Tailwind, and code Playground
by James Hughes
HTML
<table>
<thead>
<tr>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
</tr>
</thead>
<tbody>
<tr class="week1">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="week1">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="week1">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="week1">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="week1">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="week1">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
CSS
table {
width: 100%;
}
td {
height: 60px;
border:1px solid #666;
}
td {
width:14.2%;
}
td.excluded {
background-color: #6495ED;
}
JavaScript
function notPartOfMonth(week, dayOfWeek) {
var selector = "table tr:nth-of-type(" + (week + 1) + ") td:nth-of-type(" + (dayOfWeek + 1) + ")";
document.querySelector(selector).style["background-color"] = "#000";
}
function partOfMonth(week, dayOfWeek, day) {
var selector = "table tr:nth-of-type(" + (week+1) + ") td:nth-of-type(" + (dayOfWeek +1) + ")";
document.querySelector(selector).innerText = day;
}
function removeTrailingWeek(week) {
document.querySelector("table tr:nth-of-type(" + (week+1) + ")").remove()
}
// month and year are based on their actual value in dates and not index based
function fillCalendar(month, year) {
var date = new Date(year, month - 1); // month is zero based
var firstDay = date.getDay(); // day is not zero based
var daysInMonth = new Date(year, month, 0).getDate() // date is actually day of month
var currentDay = 1 // this is where we are in the loop
for(var week = 0; week < 6; week++) {
for(var dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
var beforeFirstDay = week == 0 && dayOfWeek < (firstDay - 1);
var afterLastDay = currentDay > daysInMonth;
if (!beforeFirstDay && !afterLastDay) {
partOfMonth(week, dayOfWeek, currentDay);
currentDay = currentDay + 1;
} else {
// check if we are on the last week and already past the last day
if(dayOfWeek == 0 && afterLastDay) {
removeTrailingWeek(week);
break; // break out of inner loop but this condition will only happen on the last row so this will apply to outer loop as well
} else {
notPartOfMonth(week, dayOfWeek);
}
}
}
}
}
fillCalendar(3,2014)