Archive for the ‘JavaScript’ Category

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;

Awesome list of mootools resources

Check that out, if ever I need anything mootools I will find it here.

http://www.w3avenue.com/2009/07/28/list-of-really-useful-plugins-and-resources-for-mootools/

How to shuffle an array

This is a very common programming problem, e.g. when you wish to show some images in random order, when you want to show a random quote, etc. I will show you a solution in JavaScript, but it can be ported to other languages easily.

The common solution to shuffling is to swap random elements, but swapping means you have to constantly work with two elements, and it can be done by using only one. Also, it’s common to randomly swap e.g. 1000 elements, but that wouldn’t work well for very large arrays.

All you have to do is follow a couple of simple steps:

  1. First, of course you start with a simple array, which you have in a specified order.
  2. You place a random element in the output array, and remove the element
  3. Repeat step 2 until the array is empty

Here’s the full code

function shuffle(r) {
	var pos;
	var out = [];
	while (r.length > 0)	{
		pos = parseInt(Math.random()*r.length);
		out.push(r[pos]);
		r = r.slice(0,pos).concat(r.slice(pos+1, r.length));
	}
	return out;
}

Let’s examine the parts. First, the variables pos and out are defined, and out is initialized to an empty array.

	var pos;
	var out = [];

No we “loop” through the array. But, do note that this is not a real loop, in fact we’re constantly going to remove elements until the array is empty. So the simple check on length is enough here.

	while (r.length > 0)	{

We find a random element. For large arrays the Math.random() method can be considered unreliable, but then I mean really large.

		pos = parseInt(Math.random()*r.length);

Next, we add the random element to the output array, using push. Then we remove the element from the original array. This is done in three parts:

  1. get everything on the left of the element
  2. get everything on the right of the element
  3. concat these two arrays to form a new array

That is a really difficult way of removing just one element, but deleting an element from an array is not a native javascript method. John Resig wrote another version of delete

		out.push(r[pos]);
		r = r.slice(0,pos).concat(r.slice(pos+1, r.length));

And last but not least we return the new array:

	}
	return out;
}

Example

Here’s an example of calling the function, shuffling 52 integers

var r=[];
i=52;
while (i--)
	r.push(i);
alert(shuffle(r).join(','));

Extending Array

If you feel so inclined you can make it an extension of the Array object in javascript, like so:

Array.prototype.shuffle = function() {
	var r=this;
	... //rest of code
}

Note the additional "r=this" line.

Drawbacks

There are some drawbacks and warnings to take note of:

  • It can be slow for huge arrays, I would recommend it for arrays under 1000 items
  • It takes up additional space, since it creates a new array
  • The delete can be improved, by using e.g. John Resig’s version

A shorter ‘hack’

The following is a short hack that can most definitely suit one time needs. It’s a form of sorting randomly, which sounds weird, and it is, but it works. However, if the random value is not seeded again, the next time you run it you end up with the exact same sequence.

function shuffle(r) {
  r.sort(function() { return Math.random() } );
}

For more background see e.g. the Fisher Yates shuffle method (which by the way this is not, but this is).

Javascript floating point fix

Javascript has an annoying bug feature, and it’s the wrong result of simple floating point calculations. Try this:

alert(0.1+0.2);

Surprise! The result is 0.30000000000000004.

This can be quite annoying when programming timers, and doing math of course.

Why is this? It’s because floating points work that way, it’s by design. That’s not really a flaw, it’s just to make the process real fast. Just like your pocket calculator has only 8 digits, which isn’t wrong per se, but it’s never fully mathematically correct. Sun Microsystems has some real hardcore background on the floating point issue.

But for us simple programmers, all we want is a fix, right?

Here is one at lars-sh.de. Or download the Math Library directly. Kudos to Lars Knickrehm.

JavaScript arrays, functions and objects

In javascript arrays and functions are very much alike. They are more like brother and sister than like neighbors. Arrays can hold values, which can include objects and functions. Functions can also hold these in their properties, but in addition can act as Class templates to create new objects. They are both objects by the way.

Let’s look at some data viewed in various incarnations, to illustrate the concept:

An array

var fruit = new Array();
fruit['first']='apple';
fruit['second']='banana';
fruit['third']='cherry';

Note that this uses strings as index values, creating a so-called Hash or Dictionary. It is different from a traditional array, which uses numbers as index values, as in:

var fruit = new Array();
fruit.push('apple');
fruit.push('banana');
fruit.push('cherry');

or

fruit = ['apple', 'banana', 'cherry'];

A function

var fruit = function()
{
  this.first = 'apple';
  this.second = 'banana';
  this.third = 'cherry';
}

It’s important to note that there is a major difference between a function and an object. When a function is created it can act like a constructor (class template), creating new objects with the ‘new’ keyword. Objects cannot do this themselves.

An object

var fruit = new Object();
fruit.first = 'apple';
fruit.second = 'banana';
fruit.third = 'cherry';

this can be rephrased as

fruit = {first:'apple', second:'banana'; third:'cherry'};

Note the weird ending of the line with “;};” which is correct in this case.

sIFR reloaded

 

sIFR

sIFR

sIFR (scalable inman flash replacement for the outsiders) is a technique to embed custom fonts in a webpage. You know, traditionally web pages can only show a couple of fonts reliably – the ubiquitous Arial, Times, and a couple of others.

 

When sIFR was introduced I was pretty psyched out about it. Showing any font, and still accessible, selectable, etc. However, it’s giving me nothing but headaches. Let’s recap some of those:

  • sIFR needs Flash. At a certain point there was a security issue and I had to disable Flash. No more sIFR.
  • Lots of people block Flash, because of the ads. 
  • Special characters weren’t showing. It appeared my font didn’t even have these defined. Well that’s not sIFR to blame, but still
  • It’s almost doing a good job presenting the CSS correctly. Almost.
  • Documentation? Don’t get me started. Besides a collection of pages on several blogs, that are badly maintained, there’s absolutely nothing.
  • Every time you install a new version you have to recreate your font files. Now that’s annoying!

Here are some alternatives I found today

TrueFontFamily

trademarks: JS, PHP, CSS, commercial. 

Server side generating is of course a good idea, but I can’t see if the textimages are cached, it looks like not.

Facelift

trademarks: JS, PHP, hosted, commercial

This one seems very good, but a bit too commercial. Hosted? No thank you.

TypeFace

trademarks: JS, SVG/VML, free

Typeface is a diamond among these, so it seems, if it doesn’t suffer from the lack of documentation that is. But if it’s really good it doesn’t need documentation.

The javascript Date object and how to add days to a date variable

JavaScript is not an object oriented language, it’s a prototype based language. This means that you can extend any existing object by just writing a new function for it on-the-fly. Here’s an example:

// add n number of days
Date.prototype.goto = function(n) {
	this.setTime(this.getTime()+n*86400000);
	return this;
};

Yes I know… GOTO is considered harmful. But so is Edsger Dijkstra. Anyway, this nifty little function will add, or subtract(!), any number of days with an easy to use syntax:

// add n number of days
d = new Date; // today
d.goto(7); // move it to next week
d.goto(-365); // move to last year (well if it isn't leap)
};

Try it yourself, it’s fun. Now to make things more interesting, you can make a generic function (erm.. method?!) that will calculate the number of days since the Epoch

Date.prototype.days = function() { return parseInt(this.getTime() / (1000*24*60*60)); };

This makes stuff like comparing dates and calculating differences way easier. E.g. check out this one for calculating the number of working days between two dates:

Date.prototype.workdays = function(d2) {
	var start = new Date(this);
	var end = d2;
	var ret = 0;
	var diff = end.days() - start.days();
	if (diff > 0)
		// up to 1 year
		while (start.days() < end.days() && ret < 3650)
		{
			start.goto(1); // move to next day
			if (start.getDay() != 0 && start.getDay() != 6)
				ret++;
		}
	return ret;
};

CodePress – Real Time Syntax Highlighting Editor written in JavaScript

This editor does HTML much better than tinyMCE. It would be a good idea for the “tiny” developers to incorporate color coding!

How to create a Class

It’s three articles (1 2) now, it’s almost a book! Here’s how to create a class in my three favorite languages:

PHP

Method 1: standard

The advantage of this method is it’s obvious portability to other (e.g. compiled) languages. If you add getters and setters the link to java is easily made.

class Cube {
  var $colors;
  var $size;
  var $brand;
}
$c->colors = 'red,green,blue,yellow,white,orange';
$c->size = 4;
$c->brand = 'rubiks';

foreach (get_object_vars($c) as $property=>$value)
	print_r($property . ' = ' . $value . ', ');
?>

Method 2: instant class

The advantage of this method is the fact that properties (any method or attribute) can me created on the fly, even using variables, e.g. ‘price’, ‘new’ . ‘price’ or even ‘new’ . ‘price’ . $date. So in the example below we are defining the class, but not even giving it any properties (though it could have some of course).

class Cube {}
$c = new Cube;

$prop = $colors;
$c->$prop = 'red,green,blue,yellow,white,orange';

$prop = 'size';
$c->$prop = 4;

$prop = 'brand';
$c->$prop = 'rubiks';

foreach (get_object_vars($c) as $property=>$value)
	print_r($property . ' = ' . $value . '
');
?>

Method 3: instant object

The advantage of this method is that the object doesn’t actually have a class. Because of that properties can be invented at will, and they don’t have to be variables, shortening the code to a form that looks like the class actually was defined. Be careful with this though, other people who read your code will frantically look for the class definition and won’t find it if they don’t know about the use of stdClass. An equivalent, but not as nice looking, is to cast null to an object, as in “$c = (object) null;”

$c = new stdClass();
$c->colors = 'red,green,blue,yellow,white,orange';
$c->size = 4;
$c->brand = 'rubiks';

foreach (get_object_vars($c) as $property=>$value)
	print_r($property . ' = ' . $value . '
');
?>

JavaScript

In javascript there are plenty of possibilities for creating objects. Classes however do not exist (not in a practical sense anyway). Any object you create is a ‘class’ in itself, and can be copied or extended on the fly.

Note how javascript’s for..in actually iterates over all property names (not the values as you might expect).

var c = new Object;
c.colors = 'red,green,blue,yellow,white,orange';
c.size = 4;
c.brand = 'rubiks';

for (property in c)
	alert(property + "=" + c[property]);

Though it is correct that arrays and functions are both objects, and it seems an easy way of providing php’s foreach construct, the for..in is not suitable for this. An array with 10 elements, with index 0..9 cannot be iterated this way, since the array is also a ‘Class’ and all its properties, e.g. the length property, will also be iterated. In the example below, if we added a method ’show’, we would see the definition of the function, converted to a string. That’s right, the full source code of the method.

r = Array('red','green','blue');
r.show = function() { alert(this); }
for (property in r)
    alert(property + "=" + r[property]);

(Visual) Basic

I will not consider VB.Net, since in .NET every program is object oriented (supposedly) and thus classes are at the base of the language. Anyway, it’s not more difficult than choosing “add item > class”, and almost all the code is created for you.

In Visual Basic it gets more interesting, since it’s not an OO language in itself. Again, just like in JavaScript, objects are more considered ‘containers for variables and functions’. The concept of subclassing does not exist in VB. OK, here it goes. I am assuming you have created a Standard Exe project. First, choose Project > Add Class Module. You’ll see a new module created named ‘Class1′. You can just rename that in the properties pane to Cube. Now add the code:

' method 1: public members
Public colors As String
Public size As Integer
Public brand As String

This is not the preferred way, we should actually create getters and setters for these. This is easy using Tools > Add Procedure. Name it colors e.g. and you will get the following code

Public Property Get colors() As Variant
End Property
Public Property Let colors(ByVal vNewValue As Variant)
End Property

To this you’d still have to add a private variable, such as m_colors, which would be used in your Get and Let methods. You can create a new Cube object from within a form or a module using “set c=new Cube”.

In VBA (Visual Basic for Applications) the procedure is exactly the same, though you don’t have to create a new executable. You can start by e.g. pressing ALT+F11 in Excel and you will be able to add a class module.

Finally, in VBScript you could either create a class definition as in VB (without the type names though)… or use the ExecuteGlobal method to evaluate code and, again, generate classes on the fly.

How to find out if a variable has been defined

It’s two articles now, it must be a series! Here’s how to find the out if a variable has been defined in my three favorite languages:

PHP

/* v has not been declared */
if (isset($v))
  echo "v has been defined";
else
  echo "v has _not_ been defined";

JavaScript

Please note that in javascript a runtime error would be generated when trying to access a variable that has not been defined. However, any variable that you create will automatically become a property of the window object. Therefor, checking if the variable has been added to the scope of window will result in a condition that can be checked. Also note that this will only work in a browser, which of course is how most people experience javascript anyway.

As an example: “window.doesnotexist==null” results in true. Be careful not to overwrite stuff that already does exist in the window.

/* v has not been declared */
if (window.v)
  alert("v has been defined");
else
  alert("v has _not_ been defined");

(Visual) Basic

In Visual Basic you will only be able to use this code if “option explicit” is off, meaning in VBScript, VBA and VB6.0 there should not be a line on the top which says “Option Explicit”. In the .NET environment there is a setting for this in the options dialog (project properties). In the case Option Explicit is on, variables will always be assigned a default value, so you can never check e.g. if an integer variable has been assigned a value of 0.

You can either check using the typename function or using the isEmpty function.

As an example: Debug.Print TypeName(doesnotexist)=”Empty” shows True

if isempty(v) then
  debug.print "v has been defined"
else
  debug.print "v has _not_ been defined"
end if

Next Page »