Archive for the ‘JavaScript’ Category

A physics model of a physics model

One of the hardest topics in school next to computer science is physics. Time and again I see students struggle with the topics, and I have to admit I didn’t find it easy in high school myself. So I started studying physics again using Khan Academy, and gained much insight into the basics. I have admired Sal Khan since he started his site, and as a school teacher I also think I should help him, and my students, wherever possible.

I started drawing a diagram of how all things in physics connected to each other, and while doing that, I realized there should be software to do this better. After a short search I found the wonderful D3 toolkit, based on web standards, just as I like it. D3 can create awesome diagrams, graphs, infographics, you name it.

So now I have for your pleasure and learning aid a physics based overview of common physics quantities. Click the image to see the actual animated model.

Some tips on how to use it:

  1. Click the diagram to automatically redraw it
  2. Drag nodes to change the layout
  3. Mouseover a node to see related info
force diagram physics

force diagram physics

Use in physics assignments

The colors in the diagram denote related quantities:

  • blue – essential axiomatic units m, l, t
  • green – related to movement
  • orange – related to energy
  • red – related to a single unit

To use this diagram in your physics assignment, look at the known variables. Find those in the diagram. Now see if you can combine those to make more variables: follow the arrows. If you can start from two known values you can usually calculate a third. You continue doing this until you have found the desired outcome.

Adventures in XML land: combining Excel, XML, HTML and JavaScript

the process

using Excel to generate XML, jQuery and Ajax for animations

In a past long ago I ventured into this barren land, where bugs crept up my sleeves and pants. In most cases after a short scary trip I’d be happy to be back home in PHP or plain JavaScript land.

What am I talking about? Client side “apps”, by which I mean browser based, server-less HTML pages, where everything is done on the client. Examples of such applications are CD Rom viewers, Touch Screen Console applications, and Information Display (like the train station screens).

Recently I got a request to make an Information Display. I started happily to look at how this would work using modern browser based techniques. After a couple of days of experimentation I must say that it was a wonderful journey, and I am convinced this technology will have a great future.

Ten years ago CD Roms with an HTML viewer were simple pages with little interactivity, or they came with a web server to do interesting stuff. Now, with the advent of powerful JavaScript libraries and Office 2007 we can now integrate these into a cool looking almost server-centric interactive display.

I have used the following technologies, and will explain hereafter how:

Excel 2007 and XML

Excel serves as my database. It consists of worksheets of tabular data. The data is exported to an XML file using the XMLTOOLS addin, which you can find on the microsoft site. It is very loosely designed: when I need an extra column, I insert it and start typing. I will have to re-generate an XML mapping then, and export the contents to an XML file. The advantage: the person working with this ‘database’ only needs to know Excel, and how to click on a few buttons.

jQuery and Cycle

I added jQuery most and for all for the Cycle plugin. It allowed me to create stunning visual transitions for ‘slides’. The slides are actually simple divs in an HTML page.

CSS3

I used CSS3 for creating nice looking gradients. Also I used CSS3 for zebra tables and drop shadows on images. Overall it means there is no need whatsoever for images to enhance the visuals. I think that’s how future web development will and should occur.

SVG and/or Canvas

In fact you hardly ever need both, given that these technologies mostly overlap in capability. An advantage of Canvas is that it is actually a program (javascript) instead of a declarative markup. Of course the same argument makes SVG more attractive for its simplicity.

Ultimately I decided to use SVG for both my static vector based images (floor plan) and my animation (a clock). The SVG animation actually looked better than the canvas one and I wasn’t very interested in modifying the default look.

For the floor plan I hunted for a good SVG or Canvas editor. What I found was Google Docs (!). Recently they added a diagram editor, that can export to SVG. The resulting code unfortunately looks like hexadecimal soup, but the good thing is you can easily modify the diagram on Google Docs and export again.

Right now my app only works in FireFox 3.6, and that’s just fine, baby!!

Note: I cannot share the application since it’s made for our organization, but if you need help in setting up one yourself just add to the comments…

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.setDate(this.getDate()+n*86400000);
	return this;
};



Note: Thanks to commenter Joe I use setDate instead of setTime.
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!
Follow

Get every new post delivered to your Inbox.