JavaScript Calendar Library

From CSE330 Wiki
Revision as of 22:45, 11 October 2017 by Todd (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Creating a calendar API from scratch is ambitious. To help you get started, we have written some JavaScript helper functions that take care of the "calendar math" for you. The code is available at:

For example, this is how you would make a button to load the next month and show alerts containing all the days in the weeks contained by that month.

// For our purposes, we can keep the current month in a variable in the global scope
var currentMonth = new Month(2017, 9); // October 2017

// Change the month when the "next" button is pressed
document.getElementById("next_month_btn").addEventListener("click", function(event){
	currentMonth = currentMonth.nextMonth(); // Previous month would be currentMonth.prevMonth()
	updateCalendar(); // Whenever the month is updated, we'll need to re-render the calendar in HTML
	alert("The new month is "+currentMonth.month+" "+currentMonth.year);
}, false);

// This updateCalendar() function only alerts the dates in the currently specified month.  You need to write
// it to modify the DOM (optionally using jQuery) to display the days and weeks in the current month.
function updateCalendar(){
	var weeks = currentMonth.getWeeks();
	for(var w in weeks){
		var days = weeks[w].getDates();
		// days contains normal JavaScript Date objects.
		alert("Week starting on "+days[0]);
		for(var d in days){
			// You can see console.log() output in your JavaScript debugging tool, like Firebug,
			// WebWit Inspector, or Dragonfly.

Important: JavaScript starts the months of a year, and the days of a week, at index 0. This means that in JavaScript, January is month 0, and December is month 11. Our calendar helper functions maintain this JavaScript convention.