A dead simple, lightweight javascript calendar

calendar-size-badgeI recently needed a good light weight javascript calendar but couldn’t find it. The problem is that online I could find many calendars, but they all suffered from one of two problems: they were either too heavy, or they were badly written (aka coding like it’s 1999).

I hereby present a very lightweight javascript calendar object. It can be used anywhere where you need to select a date.

It features the following:

  • no library. That’s right, it does NOT use mootools, it does NOT use jQuery.
  • clean code. Yes it can be improved, but that would make it a heavy calendar again.
  • it does not do Date magic. If you want date magic I can recommend date.js. (oh, and that means things like ‘3 days ago’ etc.)
  • it’s lightweight, mainly because it doesn’t do magic and it doesn’t have a library. It’s 2K uncompressed, 1.5K using dean edwards packer.
  • no popup windows. All

Download

Download mbcalendar 1.0

Usage

var cal = new MBCalendar('inp', 'btn', 'click');

Where

  • inp is the id of the input that will be retrieving the calendar, and
  • btn is the id of the element that will trigger the calendar to show, and
  • click is the name of the event that will trigger the calendar
  • in the onload script, in this example ‘out’ is the id of the element that will hold the calendar.

This way it can be used as a date picker, but it can also be used as a visible calendar with navigation (static). Basically the output is simply the HTML, so you can use it anywhere.

All dates van be individually styled, since they all get a unique id. Also all dates get class names so you can style either a certain year, month, or day of the month. E.g. ‘.y2009’ will style every date in 2009, ‘.m3’ will style every march, and ‘.y2009.m3’ will style every day in March, 2009.

Source code

Now for the code

/*(c) Michiel van der Blonk 2009 - license: http://www.opensource.org/licenses/mit-license.php*/

function MBCalendar(m, y)
{
this.m = m;
this.y = y;
this.weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
}

MBCalendar.prototype.$ =  function(s) {return document.getElementById(s)};

// export as array
MBCalendar.prototype.toArray = function() {
var d;
var dates = [];
for (var i=1;i<32;i++)
{
d = new Date(this.y,this.m-1, i);
if (d.getMonth() == this.m-1)
dates.push(d);
}
return dates;
};

// export as html
MBCalendar.prototype.toHTML = function() {
var i;
var ret, dayId, dayClass;
ret = dayId = dayClass = '';
var dates = this.toArray();
ret += '
<table class="cal">' + '
<tr>';
for (i in [0,1,2,3,4,5,6])
ret += '
<th>' + this.weekDays[parseInt(dates[i].getDay())].substr(0,1) + '</th>
';
ret += '</tr>
<tr>';
for (i in dates)
{
var d = dates[i];
if ((parseInt(i) % 7) == 0)
ret += '</tr>
';
if ((parseInt(i)+1 % 7==0) && i<dates .length)
ret += '
<tr>';
dayClass = 'y'+d.getFullYear() + ' m' +(d.getMonth()+1) + ' d' + d.getDate();
dayId = 'day-' + parseInt(d.getTime()/86400000);
ret += '
<td id="' + dayId + '" class="' + dayClass +'">' + dates[i].getDate() + '</td>
';
}
ret = ret + '</dates></table>
';
return ret;
};

window.onload = function() {
var $ = function(s) {return document.getElementById(s)};
var c;
$('showCal').onclick = function() {
var y = $('year').value;
var m = $('month').value;
c = new MBCalendar(m, y);
$('out').innerHTML = c.toHTML();
};
$('prev').onclick = function() {
var d = new Date(c.y,c.m-2,1);
c = new MBCalendar(d.getMonth()+1, d.getFullYear());
$('out').innerHTML = c.toHTML();
}
$('next').onclick = function() {
var d = new Date(c.y,c.m,1);
c = new MBCalendar(d.getMonth()+1, d.getFullYear());
$('out').innerHTML = c.toHTML();
}
};

If you like you can integrate the prev, next and show methods in the Calendar object itself of course. I invite all javascript experts to crunch the code even more, without making it unreadable!

If you don’t integrate that code, you will need to add some standard HTML in a page to get a functional Calendar demonstration:

<input type="text" id="year" value="" />
<input type="text" id="month" value="" />
<button type="button" id="showCal">Show Calendar</button>
<button type="button" id="prev">prev</button>
<button type="button" id="next">next</button>

Some alternative calendars you might like:

update: there was still some debug code in there, it’s removed now. Also it seems wordpress messes up the code when I paste it. Change line 16 to have the ‘<‘ char instead of &lt;

Advertisements

9 comments so far

  1. Álvaro G. Vicario on

    You should provide a downloadable version. The “copy to clipboard” feature seems to do nothing in Firefox and the “view plain” link shows HTML-encoded code that won’t run.

    Other than that, a nicely written non-bloated JavaScript calendar is always welcome.

  2. Álvaro G. Vicario on

    How exactly do you install the script? Whatever I try, I get this error:

    $(“showCal”) is null

    … triggered by this line:

    $(‘showCal’).onclick = function() {

    The code shows no other reference to an HTML element with id=”showCal” (same with “prev”, “next” and many other elements).

    Also, it’s worth noting that the script doesn’t play well with others. Doing this:

    window.onload = function(){}

    … effectively removes all on load events already attached to the window.

    • Black_Stormy on

      You need to put in the year and month (in numeric values ie 2012 and 07) in the inputs from the html snippet up there. You’ll also need to add a div with id “out” to render the calendar in. Also I think the point is that you can modify this code to suit your needs, not rip it directly and try to use it as is. In its current state it still needs a bit of tweaking to integrate it anywhere.

  3. John on

    This isn’t even remotely complete code…

    • Michiel van der Blonk on

      Well, it works for me. I don’t know what you consider complete, but in essence a calendar is to show dates, and a date picker it to select a date. Anything else is extra.

      I did notice year and month missing, will add those.

  4. Tri on

    Can you show an actual example of the calendar at work? thanks.

  5. Black_Stormy on

    You may want to add in your snippet of HTML that a div with id “out” is required to print the calendar to. Also it is definitely nice and lightweight but the days change location for each month, so that the dates stay in the same spot. This is the opposite to a normal digital calendar and counter-intuitive. I’m sure a little more code to add that base functionality wouldn’t be too big a deal. Nice calendar otherwise, does what it says on the box, with some fiddling to figure it out.

  6. Heniu on

    WTF is this? It does not work. (dates[i] is undefined… and many more)

  7. Jacob King on

    This code works, see it here on jsfiddle https://jsfiddle.net/jacobuid/quh4fv64/

    enter the month then day and see the magic!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: