JSFiddle - React, Tailwind, and code Playground
by kpulkit29
HTML
<div class="container">
<h1 class="month"></h1>
<table cellspacing="0">
<thead>
</thead>
<tbody></tbody>
</table>
</div>
<!-- while (true) {
if (rem < 7) {
let diff = rem - 1;
if (currentDayIndex - diff < 0) {
firstDayIndex = 7 - Math.abs(currentDayIndex - diff);
} else {
firstDayIndex = currentDayIndex - diff;
}
break;
} else if (rem == 0) {
firstDayIndex = currentDayIndex
break
}
} -->
CSS
td {
width: auto;
padding: 10px;
border: 1px solid black;
}
JavaScript
function getDays(year, month) {
return new Date(year, month + 1, 0).getDate();
}
function CalenderBuilder() {
this.weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const date = new Date();
this.date = date;
this.monthIndex = date.getMonth();
this.year = date.getFullYear();
this.initialize();
}
CalenderBuilder.prototype.addDates = function() {
const tbody = document.querySelector("table tbody");
tbody.innerHTML = ''; // Clear previous dates
const firstDayIndex = new Date(this.year, this.monthIndex, 1).getDay();
const totalDays = getDays(this.year, this.monthIndex);
let arr = new Array(42).fill(null);
for (let i = 0; i < totalDays; i++) {
arr[firstDayIndex + i] = i + 1;
}
for (let i = 0; i < 6; i++) { // 6 weeks (max)
let tr = document.createElement('tr');
for (let j = 0; j < 7; j++) { // 7 days
let td = document.createElement('td');
let date = arr[i * 7 + j];
td.innerText = date ? date : '';
tr.appendChild(td);
}
tbody.appendChild(tr);
}
document.querySelector(".month").innerText = new Date(this.year, this.monthIndex).toLocaleString('default', { month: 'long' }) + ' ' + this.year;
}
CalenderBuilder.prototype.prev = function() {
this.monthIndex--;
if (this.monthIndex < 0) {
this.monthIndex = 11;
this.year--;
}
this.addDates();
}
CalenderBuilder.prototype.next = function() {
this.monthIndex++;
if (this.monthIndex > 11) {
this.monthIndex = 0;
this.year++;
}
this.addDates();
}
CalenderBuilder.prototype.initialize = function() {
let tableHeader = document.querySelector("table thead");
let tr = document.createElement('tr');
for (let day of this.weekdays) {
let th = document.createElement("th");
th.innerText = day;
tr.appendChild(th);
}
tableHeader.appendChild(tr);
...