Archive for June, 2008

Taming Javascript – a few pointers for developers new to Javascript…

I’ve never had to build any large projects in Javascript until recently, and when the day finally arrived I found myself short of some fairly crucial knowledge.

[Just a quick note to anyone who previously downloaded any of the scripts available on my blog, I recently re-coded all of them and provided documentation for the Lightbox and PictureGallery libraries.]

My biggest mistake was to make assumptions based on my knowledge of other programming languages. During my years as a developer I’ve coded large projects in C/C++, Java, Perl and Python, I’ve also played around with quite a number of other languages including Javacsript. Unfortunately, and to my cost, this gave me a predetermined viewpoint of how Javascript would behave, and well, here are some things to be aware of.

Always, always use var to declare variables

The most important behaviour to be aware of is Javascripts scope handling. The first mistake I made was to ignore the var keyword when declaring variables. If you don’t explicitly declare a variable using var then Javascript will implicitly create it as a global scope variable. The only way to declare a local scope variable is by using var. Of course Most languages have some way of declaring local and global variables, and they differ in how they support it, the real gotcha in Javascript is the lack of block level scope.

Scope is limited and retrospective

Scope applies only globally or within the body of a function, scope does not apply to loops or conditionals. The reason for this limited support (as far as I understand) is that scope is handled in Javascript by two objects one which holds global variables as properties, and one which hold local variables as properties, the later of which is called the call object. The call object is made available to a function at the point that it’s called, and this has interesting results, consider the following code;

var developer_name = "Anthony";
function shout_at_developer() {
	alert( developer_name );
	var developer_name = "John";
	alert( developer_name );

You might expect the code above (as I did) to open an alert box the first time with the message “Anthony” in it, and the second time with “John”, but that’s not what happens. What actually happens is that the first alert box contains the content “Undefined”. Why? Well, because the local variables are stored against the call object, when you declare a variable local to a function it doesn’t matter where you declare it, it will exist within the scope of that function.

So, whenever you declare a variable it’s a good idea in most cases to declare it at the top of the function (since position is irrelevant), and don’t forget that declaring a variable inside a loop or conditional statement will not make it local to that statement, only to the function that statement is defined within.

Browser limitations (or how to kill the web browser)

If your writing anything that could potential loop forever (or a very long time) take care, one of the big issues that I came across is the lack within browser Javascript interpreters to call a sleep (a.k.a delay, wait, etc.) function. Effectively this means all loop operations are CPU intensive since there is no way of handing back CPU time for a period each cycle, this is also a problem in code where functions call themselves to achieve looping or recursive flow.

It’s a good idea to put safe guards in, for example limit a loops iterations using a fail safe count;

var iteration_count = 0;
var max_iteration_count = 1000;
while ( true ) {
	// Do something...
	if ( iteration_count > max_iteration_count ) {
		throw Error( "Too many iterations in loop" );

Browsers vary so testing is crucial

Every web developer is aware of the issues that come with trying to build websites that behave identically across all the leading browsers. Anyone who wants to keep their sanity will use an existing library to minimize how much of this they’ll have to cater for themselves, for example I use the excellent jQuery. But I’m afraid this isn’t going to solve all your problems, there’s quite a few subtle differences between the browsers and since you unlikelybe aware of all them in advance (especially if like me you only use Javascript from time to time) you will need to test thoroughly on any browser you intend to support. Never assume that if your code works in one browser it will work in another, even if the browser only differs by version.

A couple of the most annoying gotchas I came across were specific to Internet Explorer (a.k.a IE), which as standard does not yet provide a useful Javascript debugger (role on verison 8).

IE does not support the following syntax for assigning multiple values returned from a function,

function get_developer_list() {
    return [ "Anthony", "John", "nick" ]
var [ developer_a, developer_b, developer_c ] = get_developer_list();

This syntax is supported by both Firefox and Safari, where as IE didn’t provide me with any debug information (not even a warning) for this issue, it just stopped running the code after this point. To support for all of the browsers I assign the values to a list and then assign each item through their index afterwards.

Another small difference in IE’s syntax support, which isn’t really an issue but it did catch me out, is that you can’t leave trailing commas in dictionary declarations, for example;

var developer_data = { "Anthony" : "...", "John" : "...", };

Now, potentially of course you could argue this should throw up an error, but since IE doesn’t care if you do the same thing in lists, and again provides no or only minimal debug information, it can be a frustrating bug to find.

It’s not that bad really…

Despite my frequent jibes and general pessimistic take on having to write Javascript code over the last few weeks, having cast off my assumptions and given the language the time and attention it deserves, actually Javacsript is really quite a nice language (and I’m a bitter and biased developer, or so it would seem).

It’s never going to be my favourite, but at least it does have a rich feature set including good (though yet again quirky) support for object-oriented programming, and a built in regular expression engine.


Up, down & famfamfam…

So things are going a little slower than I’d like with the development of the prototype for iido, still I managed a concerted effort today to make a start.

The first challenge was to update my Qt and PyQt installations, which I have to say (if memory serves me correct) with version 4.4+ is a much easier task than with previous versions. One gottcha you might want to watch out for (possibly Windows OS specific) is forgetting to uninstall the previous version of Qt, this can cause PyQt to try and access the wrong QtCore4.ddl and then your application wont run. Thankfully the solution is simple, just uninstall the previous version of Qt and your set.

Back on subject, once my system was up-to-date I was able to make a reasonable amount of progress. In these early stages I’m still putting inplace quite a bit of framework to support the management of widgets, however with some basic widgets visible and draggable (just using the Qt draggable flag at the moment), I realised that I hadn’t considered the overlapping/z-index of widgets.

To solve this I am putting in place a simple stack style transformation that allows the user to (see the screen-shot),

  • Bring the widget to the front
  • Send the widget to the back
  • Bring the widget up one Z position
  • Send the widget down one Z position

Early screen-shot of the prototype iido application

However, there are a number of issues still to be resolved,

  • The Z position is relevant to all widgets so it might take several clicks for a user to move a widget above a desired widget
  • When a user wishes to transform a widget using the transformation regions, the region they require maybe hidden, to resolve this the user would have to move the widget so that the region was visible.

I think the Z position issue can be resolved by building in another couple of transformation options that allow the user to move the widget in front or behind a specific widget (this may eliminate the need for the up/down one option). There might also be some merit in allowing users to specify a specific Z position in which case we would need to make the Z position of all widgets visible. As for hidden transformation regions I am open to suggestions, though I think I may need to have a function model before a decision can be made.

Finally I’d like to credit the famfamfam icon set which I am using whilst developing iido, this is a professional quality set of icons available from under the creative commons license ( Producing icons is a hugely time consuming process and my sincere thanks goes to the creator Mark James for his efforts and generosity.

A simple JS finite state machine

Now I know I said I wouldn’t have an excuse to produce anymore javascript libraries for a while, but I should have known that would ensure my fate. My current project is a javascript application that supports numerous states, after trying at first to manage these using a large (then larger series) of if tests, I gave up and put together a simple finite state machine FSM to resolve the transitions.


The download contains an example.html file, open/view this for the demo. Tested in IE 6/7, Firefox, Opera and Safari.

A new kind of widget, a leaf…

One of the major areas of development in the iido application will be the custom interface. Though typically in designing a user interface I would try to avoid the creation of non-standard (and therefore non-familiar) interface components, because of the interactive requirements of the iido application some custom components are inevitable.

The first of these components being examined is the leaf widget, which is actual a sort of cross between a standard window and a general purpose flow diagram box. The reasons for calling this new hybrid widget a leaf is that,

  • it represents a leaf of paper (all be it a feature rich leaf of paper),
  • it floats on the interface surface (can be thrown and spun),
  • it can be linked to other leaves via one or more branch (ok, I’m pushing the anologies here, but you get the idea).

Those of you who’ve had the (I’ll say…) experience of working with me will be use to me trying to over add meaning to names, but it’s only a working title for the time being so indulge me.

At the current time what Andy and I are looking at prototyping is user interaction with widgets, and in the short-term we’re concentrating on transformation, the following image provides an overview of the how a user might be able to move, rotate and resize a leaf widget.

Transformation of leaf widgets

The leaf widget will provide move, rotate and resize functionality all via a single mouse button, regions around the border of the leaf will provide the user with access to the various transformations. Regions will only appear once the user mouses over the leaf widget, and will (as can be seen in the image) be highlighted (including a guide) once they are activated by a mouse click.

I’m going to be putting together a basic prototype of the leaf widget in Python and Qt over the next few weeks, the source will be made available to those who are interested in running it, I’ll also provide a video for those less adventurous.

Again, all feedback and ideas greatly appreciated. It’s been really good to hear what people see as requirements for such an application, and I’d really like to know what people think of the non-standard transfomation idea.

A simple JS gallery

Yet another small JS library that I’ve produced as part of a current project. This time it’s a simple Javascript picture gallery that supports a sliding thumbnail flow. This replaces an earlier design that used dragging instead of sliding – as a friend kindly pointed out to me, this was annoying since it meant to activate an image you had to double click.

I wont have any excuses to produce more JS libraries now for a little bit (oh dam!), and though I’m really not a fan of Javascript I would recommend the JQuery library (and it’s plugins), which has made the last few days of development bearable.


To customize your gallery modify the picture-gallery.html and picture-gallery.css files, for documentation see the picture-gallery.js and picture-gallery-setup.html files.


The download contains a picture-gallery-setup.html file, open/view this for the demo. Tested in IE 6/7, Firefox, Opera and Safari.

First glimpses…

As promised I’ve uploading a visual of how the iido interface might look. The visual is simplified (only showing 2 lists and a single connection), but it’s a starting point for discussion. In actual fact over the last few weeks Andy and I have made several design descisions based on simple prototypes, and a more upto date version of the interface (including more visuals) will be discussed in the next blog, which is concerned with user/object interactions in particular transformations.

So to the visual…

iido interface first visual

A couple of things about the visual,

  • No tree-view association, lists can be linked in parent>child or in sibling format. However, these relationships are then shown by lines, not necessarily by position.
  • Lists are shown in a custom looking window, the window (which I call a Leaf widget) is currently the core subject of my prototyping, the idea is these can be thrown (moved), spun (rotated), resized, and minimized – the look and feel of these has changed a bit over several revisions.
  • The little colour icon on the bottom toolbar indicates that it will be possible to style individual lists, either with preset styles or individually (the resize icon should be ignored as this is something that has changed in the new prototype).
  • The visual only shows two linked to-do lists, the plan is that a Leaf may contain any sort of content, images, a list of contacts, flow digrams, spreadsheets…

So hopefully this will spark something in you guys, even if it’s abject hatred, let me have it all.

A simple JS lightbox

For the project I’m working on at the moment I’ve had to build a Lightbox class (similar in behaviour to the well known lightview library).

I’m listing it here for those of you who might wish to use it – if you do use it then I’d love to know where and what for, other than that have fun.

To customize your lightbox modify the lightbox.html and lightbox.css files, for documentation see the lightbox.js and lightbox-setup.html file.


The download contains an lightbox-setup.html file, open/view this for the demo. Tested in IE 6/7, Firefox, Opera and Safari.