Last active
March 23, 2017 22:56
-
-
Save mnewt/1f7388ef1a9a8872d5d0b247d099bd73 to your computer and use it in GitHub Desktop.
Print a simple HTML calendar using javascript with no dependencies (except pure.css)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.format = function() { | |
var args = arguments; | |
return this.replace(/{(\d+)}/g, function(match, number) { | |
return typeof args[number] != 'undefined' | |
? args[number] | |
: match | |
; | |
}); | |
}; | |
Date.prototype.monthDays = function() { | |
var d = new Date(this.getFullYear(), this.getMonth()+1, 0); | |
return d.getDate(); | |
} | |
Date.prototype.firstWeekdayOfMonth = function() { | |
var d = new Date(this.getFullYear(), this.getMonth(), 1); | |
return d.getDay(); | |
} | |
Date.prototype.formatMonth = function () { | |
const monthNames = [ | |
"January", "February", "March", | |
"April", "May", "June", "July", | |
"August", "September", "October", | |
"November", "December" | |
]; | |
return monthNames[this.getMonth()]; | |
} | |
function calendar (month) { | |
const calendarDayHTML = '<div class="pure-u-1-8 calendar-day">{0}</div>'; | |
var html = ` | |
<div class="pure-g calendar-table"> | |
<div class="pure-u-1"> | |
<h3>${month.getFullYear()} ${month.formatMonth()}</h3> | |
</div>`; | |
// Insert blank space for weekdays falling on previous month | |
for (i=month.firstWeekdayOfMonth(); i>0; --i) { | |
html += calendarDayHTML.format(' '); | |
} | |
// Print days | |
for (i=0; i<month.monthDays(); ++i) { | |
((month.firstWeekdayOfMonth() % 7) == 0) ? html += calendarDayHTML.format(' '): ''; | |
html += calendarDayHTML.format(i+1); | |
} | |
return html; | |
} | |
var root = document.getElementById('calendar'); | |
root.innerHTML = calendar(new Date); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="calendar"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment