Skip to content

Instantly share code, notes, and snippets.

@KevinWang15
Last active March 4, 2018 08:21
Show Gist options
  • Save KevinWang15/5a2ade1a291caf3a00e8d08d551bde45 to your computer and use it in GitHub Desktop.
Save KevinWang15/5a2ade1a291caf3a00e8d08d551bde45 to your computer and use it in GitHub Desktop.
JS Calendar - super simple & customizable, written in the form of angularjs, with calendar layout algorithm / "show today".
// adapted from https://stackoverflow.com/a/13786155/6247478
var cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var day_names = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
angular.module('demo')
.directive('calendar', function () {
return {
restrict: 'E',
templateUrl: 'templates/calendar.html',
replace: true,
scope: {
data: '=',
delegate: '=',
year: '@',
month: '@',
},
link: function (scope, elem, attr) {
scope.rep7 = [0, 1, 2, 3, 4, 5, 6];
scope.weekHeaders = day_names;
var shift = 0;
var today = new Date();
var year = +scope.year;
var month = +scope.month;
var firstDay = new Date(year, month, 1);
var startingDay = firstDay.getDay();
var monthLength = cal_days_in_month[month];
if (this.month === 1) {
if ((this.year % 4 === 0 && this.year % 100 !== 0) || this.year % 400 === 0) {
monthLength = 29;
}
}
scope.monthName = month_names[month];
scope.calendarData = [];
var day = 1;
for (var i = 0; i < 9; i++) {
scope.calendarData.push(['', '', '', '', '', '', '']);
for (var j = 0; j <= 6; j++) {
if (day <= monthLength && (i > 0 || j + shift >= startingDay)) {
var isToday = (+scope.year === today.getFullYear() && +scope.month === today.getMonth() && day === today.getDate());
scope.calendarData[i][j] = { text: day, isToday: isToday };
day++;
} else {
scope.calendarData[i][j] = { text: "" };
}
}
if (day > monthLength) {
break;
}
}
}
}
});
.calendar-table {
table-layout: fixed;
width: 100%;
tr.month {
background: #888;
padding: 6px 0;
color: white;
font-weight: bold;
}
tr.calendar-header {
background: #AAA;
td {
border: 1px solid #888;
text-align: center;
}
}
tr.days{
background: white;
td{
border: 1px solid #AAA;
text-align: center;
padding: 10px 0;
}
td.today {
background: #fafbca;
}
td.not-available {
background: #E3E3E3;
}
}
}
<table class="calendar-table">
<tr class="month">
<th colspan="7">
{{monthName}} {{year}}
</th>
</tr>
<tr class="calendar-header">
<td ng-repeat="i in rep7 " class="calendar-header-day">
{{weekHeaders[i]}}
</td>
</tr>
<tr class="days" ng-repeat="row in calendarData track by $index">
<td ng-repeat="day in row track by $index"
ng-class="{'today':day.isToday,'not-available':!day.text}">
{{day.text}}
</td>
</tr>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment