Category: Programming

  • Javascript-generated tables and rowspan

    At work, I’ve recently been putting together a nice little calendar-like utility using Javascript. Basically, it has to generate a table consisting of cells which may span multiple rows. Surely the solution is simple enough: just set the rowspan on each td as we create it. Unfortunately, that doesn’t work, at least not in Firefox.

    It appears that in Firefox, if you create a td and set its rowspan to some value when there are no rows for it to expand into, the attribute will be completely ignored, even if you add rows afterwards! Needless to say, this is very annoying. The solution? Build your table backwards.

    The code I have now is something like this (note that I’m developing using the Mootools framework):

    [sourcecode language=’javascript’]var tbl = new Element(‘table’);
    var trs = [];

    for (var i = 0; i < 4; i++) { var tr = new Element('tr'); tr.grab(new Element('td', { 'html': 'Cell ' + i })); if (i % 2 == 0) { tr.grab(new Element('td', { 'rowspan': 2, 'html': 'Span ' + (i / 2) })); } trs.push(tr); }for (var i = trs.length - 1; i >= 0; i–) {
    tbl.grab(trs[i], ‘top’);
    }[/sourcecode]

    What does this code do? Well basically, we’re creating a table with ten rows and two columns; the cells in the right-hand column each occupy two rows. The result will be something like this:

    Cell 1Span 1
    Cell 2
    Cell 3Span 2
    Cell 4
  • MooTools and OO Javascript development

    I’ve started work on a new project at my job — a fairly complex AJAX application for the education sector. For this project, I’ve been allowed to essentially choose my own direction, and I’ve chosen to implement the clientside Javascript using the MooTools framework. I’ll say it right here: I’m absolutely loving it.

    What I’m really enjoying about MooTools is the object-orientedness it brings to development. Although syntactically it’s a little bit weird at first, the ability to create, extend, and implement classes makes my development progress much more quickly, and in a more efficient way. Add to that the plethora of utilities (like the .each prototype for arrays) and shorthand functions (like $ to replace document.getElementById), and all of a sudden Javascript development becomes a bit more, well, flexible.

    I’m not saying that you can’t accomplish cool things in Javascript outside of MooTools (or other frameworks, for that matter); my point is that I believe you can accomplish cool things in Javascript more quickly using a good framework, which should really come as no surprise. Perhaps the reason I’m so enjoying this type of development, to the point of blogging about it, is that up till now, I’ve been stuck working in a non-frameworked, very non-OO Javascript development paradigm.

    I mentioned the curious syntax that accompanies MooTools.  To create a new class, for example, you would probably write something like this:
    [sourcecode language=’javascript’]var myClass = new Class({
    Implements: Options,
    options: {
    optionA: ‘monkey’,
    optionB: ‘pony’
    },
    initializer: function(options) {
    this.setOptions(options);
    this.doSomeStuff();
    },
    doSomeStuff: function() {
    alert(this.options.optionA + ‘ eats ‘ + this.options.optionsB);
    }
    });[/sourcecode]
    And then you would initialise it like this:
    [sourcecode language=’javascript’]var myInstance = new myClass({
    optionA: ‘Big Pony’
    });[/sourcecode]
    Although it looks a bit weird, it’s actually not too bad. There are really only two problems I have with it:

    1. Remembering to put commas in all the right spots.
    2. Geany, my preferred IDE (cf. Geany IDE: Tango dark colour scheme) can’t pick up classes and members properly (actually, at all) in this style.

    Other than that, though, I’m really enjoying it.

  • HTML Entity Reference

    What’sMyIP.org have a fantastic HTML Entity Reference which can optionally display every single character known to man (or seemingly so). It’s the most exhaustive and well-presented entity reference chart I’ve found on the web, so I thought it was worth pointing it out.

  • New theme!

    I’ve finally got around to replacing the placeholder theme I had on the site. The new theme that I’ve made is much cleaner, simpler, and fresher.

    This new theme is built around the Sandbox WordPress theme. Sandbox provides you with a really well marked-up document, with appropriate classes, ids, and so on where you need them — essentially, it lets you build the entire theme in CSS without having to worry about the markup, and in so doing, encourages you to build a CSS-only design. I’m proud to say that this design is wholly CSS — there is no extraneous markup, and there are also no browser-specific hacks or files: everything is contained in a single CSS file and about five images, for a total size of around 40kB.

    I should also note once again that Firebug is, perhaps, the best tool for web development, be it design or coding — about 90% of the styling was tested in the browser using Firebug before being applied in the CSS file itself.

    Comments, questions, or criticisms of the new design? Just leave them in the comments.

  • Web developer tools

    In this post, I’ll outline some of the web developer tools available in the major browsers: Firefox, Internet Explorer, Opera and Safari. This is a wholly subjective post, based on my experience as one of two developers on a very large AJAX application at Saron Education.

    Firefox

    Firefox has arguably got the best web development tools available, all of which can be downloaded from the Firefox Addons site. The two which I find most useful are the Web Developer Toolbar, by Chris Pederick, and the often-copied Firebug (official website), which itself sports a variety of addons.

    Web Developer Toolbar

    The web developer toolbar is useful for quickly enabling and disabling features of your site, checking CSS, emulating mobile browser rendering, and controlling Firefox more precisely. Personally, I find its most useful features are the ability to:

    • Disable the browser cache entirely, which removes the need for Control-Refresh or cache-clearing;
    • Outline deprecated elements, or any particular set of elements in a variety of fashions, which is very useful for updating old sites;
    • Extract colour information from the current website; and
    • View the cookie information for the current site.

    Download the Web Developer Toolbar

    Firebug

    I sometimes wonder how I ever managed to develop web applications without Firebug. Firebug allows you to alter CSS styles on the fly, edit the HTML contents of the page on the fly, visually watch the DOM being changed by your scripts, debug your scripts, type and run JavaScript straight from the browser, visualise network activity, inspect XMLHttpRequests, and much much more besides. Firebug is, in my experience, the most mature, stable, and efficient of all the tools in this survey.

    The features of Firebug which I find most useful are:

    • The ability to ‘inspect’ the DOM visually (by clicking on elements within the page), then alter their attributes, styles, and even their content dynamically;
    • The ability to watch the effects of DOM alterations by running scripts;
    • The console, with which you can craft and run JavaScript which is run as though it were part of the page itself;
    • The network monitor, which allows you to view all the POSTs and GETs your XMLHttpRequests create.

    Download Firebug

    Internet Explorer

    Until IE 8, the tools available to developers in IE were woeful at best. Fortunately, however, Microsoft has got their act together, and mimicked Firebug for version 8. The features made available in this tool include

    • The ability to interrogate the DOM to view style information about elements (changing attributes and styles hardly ever seems to work in the latest Beta, so viewing them is all you can really achieve);
    • A console, with which you can craft and run Javascript as though it were embedded in the page;
    • Javascript debugging.

    Unfortunately, these tools are still very much in beta, and are very buggy. As I mentioned, altering element attributes and styles hardly has any effect. Also, the CSS inspection system is poorly laid out and often just plain wrong. The console is well-implemented. The entire system is definitely a step in the right direction, but it suffers from bugs and lack of innovation. Also, it seems to slow down and destabilise the entire browser.

    Internet Explorer 8’s developer tools are built in; access them with the F12 key.

    Opera

    Opera’s developer tools, codenamed ‘Dragonfly’, sit between Firebug and IE in terms of functionality and facility. The DOM inspection and manipulation tools work really well (as well as Firebug), and are more immediately configurable, thanks to a variety of toolbar buttons. Dragonfly doesn’t have a console; rather, it uses a ‘command line’ interface. The difference is that where the console in Firebug and IE has seperate areas for input and output (what you type and what it does), the command line mixes these two together, much like a Unix shell or DOS. Personally, I prefer the console paradigm, but it’s much of a muchness.

    Opera’s Dragonfly is built in; access it by going to Tools -> Advanced -> Developer tools.

    Safari

    As with most Apple products, the developer tools in Safari are very pretty. There is a console akin to that in Firebug and IE, and you can inspect and manipulate the DOM. Unfortunately, however, the tools are quite buggy, and often fall down. Whilst the tools are very pretty, they don’t seem to be as stable even as IE 8’s.

    Safari’s web developer tools are built in; access them enabling the develop menu from the Advanced tab of the config, then choosing the appropriate menu item from the Develop menu.

    Conclusions

    Whilst Firebug is still by far the best tool available for web developers, the widespread development of tools by browser developers means that cross-browser debugging and development is becoming ever easier. Hopefully the tools will foster competition, so that feature sets and stability improve in all the tools.

  • Cross-browser div focus and blur

    Internet Explorer has for some time supported giving ‘focus’ to non-focussable elements such as divs. Firefox, by contrast, does not. Whilst this makes sense semantically, it’s often still very useful to use these triggers. For example, you can use onfocus to show a popup when a div is clicked, and close the popup when anything else is clicked on the page (in the onblur event).

    There are many, many workarounds which provide this functionality, using such tricks as hidden input elements, global onclick handlers, and so on, but the simplest is simply this: give your div a tabIndex attribute. For example,

    [sourcecode language=”html”]

    Click to show another div.

    [/sourcecode]
    works perfectly in Firefox, Internet Explorer, and Chrome as shown in the example below:

    Click to show another div.

    You can also achieve a similar effect purely with CSS:

    [sourcecode language=”html”]

    Focus me!
    Hooray!

    [/sourcecode]

    Focus me!
    Hooray!

    Because the second example shows or hides a child element, the parent element will remain focussed if the user interacts with the child element, or its children. This allows you to embed links, forms, videos, and so on in the child element.

    The value of tabIndex can have significance, too:

    • -1: The user can’t tab to the element, but it can be given focus programmatically (element.focus()) or by being clicked on.
    • 0: The user can tab to the element, and its order in the tabbing is automatically determined.
    • >0: Give the element a priority, with ‘1’ being the highest priority.

    I originally discovered this technique on this CodingForums.com thread.

  • Mobile phone drum machine

    This is my first project using Mobile Processing. It’s essentially a MIDI drum machine, with five preset drums: kick, snare, open/closed hihat, and cowbell. Each row represents a ‘tick’, and when you press play, each tick is played in turn. It has been tested on a Sony Ericsson K800i.

    Note that at the moment, you can’t change the tempo, can’t load or save patterns, can’t have more than one pattern, and can’t choose which drums to use. I might include those features in a later release. For the moment, though, it’s a fun way to waste a few minutes.

    View the applet in your browser (and source)

    Download the applet for your phone

  • Grass

    This is based on the leaves from “Droplets”. Essentially, the leaves are turned on their sides, and become blades of grass, pushed (or, if you’re poetic, ‘caressed’) by the wind. Each blade is made up of up to 17 particles: a root particle, which anchors the entire blade, and then a series of particle pairs describing its position. Each pair has a fixed particle which is the ‘preferred’ point for that node, and a flexible particle, which can move freely. These pairs are connected with springs, and each flexible particle is also connected to the flexible particle before it with a spring. This keeps everything together but moving fairly organically.

    View the applet (and source)

  • Droplets

    This was an attempt at getting to grips with the Traer Physics library. Basically, droplets of water fall from the top of the screen, land on a couple of leaves, join up to form larger droplets, and then, when they’re too heavy, fall off again. The collision detection used isn’t fantastic, so you’ll notice some strange droplet behaviour every now and then.

    View the applet (and source)

  • Energy

    A musical project.

    The first thing you’ll notice is that this is atonal. I did initially work with a fixed key (E minor, in fact), and experimented with a variety of other keys, too; everything from simple triads to pentatonics, seventeen tone equal temperaments, and even a completely random set of frequencies, but overall, I think that a three octave span of twelve tone equal temperament frequencies is the most effective.

    The sounds are generated on-the-fly; they are simple sine waves with a decay. Internally, the x-coordinates of the particles are broken into a series of ‘frequency bars’. Particles move along, building up energy, and eventually release this energy as a musical tone; the frequency is determined by the bar they are in. The frequencies are randomised.

    Left clicking will create a ‘beat-particle’ for the frequency bar under the cursor. These particles will emit a tone every 2, 4, or 8 quantisations. Right clicking creates a ‘pulse-particle’, which emits a tone every x quantisations, where x is randomly determined.

    Also in the code, but not enabled in the applet, are ‘orbit particles’ – these are the same as normal particles, but they choose a normal particle to follow as quickly as their current energy level will allow them to. They have a 5% chance of changing their target every tick.

    If you run the applet, you will probably notice that the audio and the visuals are not perfectly in sync; unfortunately, this is a drawback of the Java sound API in conjunction with all of the maths and rendering going on every drawing cycle (at around 60 frames per second).

    Download a post-processed MP3 created using this applet

    View the minimal atonal applet (and source)

    View the full applet (in E minor, no source)

  • Swarms

    A swarm of particles that move around together. Particles are of two sexes, and can reproduce when two particles of opposite sex touch. Particles grow old and die; the younger they are, the faster they can move.

    View applet (and source)

  • Particle Swarm Optimisation

    A simple visualisation of Particle Swarm Optimisation in a 2D plane.

    View applet (and source)