Category: Web design

  • Quicksort an array of objects

    Often, you will need to sort an array of objects in Javascript. The inbuilt sort() function can’t do this, but here is a Quicksort implementation for doing just this.

    Parameters

    array The array to be sorted. (See below for an implementation on the Array Native itself, which makes this variable unnecessary).

    key The key to sort by. Make sure every object in your array has this key.

    Examples

    [sourcecode language=’javascript’]
    var objs = [
    {fruit:”cherry”},
    {fruit:”apple”},
    {fruit:”banana”}
    ];

    console.log(objs.sortObjects(‘fruit’));
    // Logs [{fruit:”apple”},{fruit:”banana”},{fruit:”cherry”}] to the console
    [/sourcecode]

    The code

    [sourcecode language=’javascript’]
    sortObjects: function(array, key) {
    for (var i = 0; i < array.length; i++) { var currVal = array[i][key]; var currElem = array[i]; var j = i - 1; while ((j >= 0) && (array[j][key] > currVal)) {
    array[j + 1] = array[j];
    j–;
    }
    array[j + 1] = currElem;
    }
    }
    [/sourcecode]

    Implemented on the Array native:

    [sourcecode language=’javascript’]
    Array.implement({
    sortObjects: function(key) {
    for (var i = 0; i < this.length; i++) { var currVal = this[i][key]; var currElem = this[i]; var j = i - 1; while ((j >= 0) && (this[j][key] > currVal)) {
    this[j + 1] = this[j];
    j–;
    }
    this[j + 1] = currElem;
    }
    }
    });
    [/sourcecode]

  • Javascript string ellipsising

    Putting ellipses into strings that are too long has been around for a very long time. Unfortunately, Javascript doesn’t offer a native method of doing this, so below is a little function that’ll do it for you.

    This function returns a copy of the string it’s called on, ellipsised, and takes three parameters:

    toLength (required) The number of characters to truncate the string to (or 0 to disable ellipsising)

    where (optional, default ‘end’) A string representing where the ellipsis should be placed — ‘front’, ‘middle’, or ‘end’

    ellipsis (option, default ‘\u2026’) A string to be used as the ellipsis.

    Examples

    [sourcecode language=’javascript’]
    // Our clichéd string
    var s = ‘Jackdaws love my great big sphinx of quartz’;

    alert(s.ellipsise(10));
    // Alerts “Jackdaws l…”

    alert(s.ellipsise(10, ‘front’));
    // Alerts “… of quartz”

    alert(s.ellipsise(10, ‘middle’, ‘pony’));
    // Alerts “Jackdponyuartz”[/sourcecode]

    The code

    [sourcecode language=’javascript’]String.implement({
    ellipsise: function(toLength, where, ellipsis) { // Where is one of [‘front’,’middle’,’end’] — default is ‘end’
    if (toLength < 1) return this; ellipsis = ellipsis || '\u2026'; if (this.length < toLength) return this; switch (where) { case 'front': return ellipsis + this.substr(this.length - toLength); break; case 'middle': return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2) break; case 'end': default: return this.substr(0, toLength) + ellipsis; break; } } });[/sourcecode]If you're not using MooTools, you can use this variant instead:[sourcecode language='javascript']String.prototype.ellipsise = function(toLength, where, ellipsis) { // Where is one of ['front','middle','end'] -- default is 'end' if (toLength < 1) return this; ellipsis = ellipsis || '\u2026'; if (this.length < toLength) return this; switch (where) { case 'front': return ellipsis + this.substr(this.length - toLength); break; case 'middle': return this.substr(0, toLength / 2) + ellipsis + this.substr(this.length - toLength / 2) break; case 'end': default: return this.substr(0, toLength) + ellipsis; break; } }[/sourcecode]

  • Internet Explorer DOMDocument & XPath

    I discovered a couple of interesting things about Internet Explorer’s MSXML2.DOMDocument object. It turns out that there are essentially two “production-quality” versions of it available: 3.0 and 6.0. Version 6.0 is much the better version, but it’s quite new, and not available on all systems. This means that in IE7 and IE8, instantiating a new MSXML2.DOMDocument object gives you version 3.0.

    Now most of the time, this isn’t a problem. Today, though, I was constructing an XPath expression that used the substring() function; something like this:

    [sourcecode language=’xml’]//Element[substring(Child, 1, 3)=’abc’][/sourcecode]

    This will pull all Elements with a Child element whose value’s first three characters are “abc”. Not particularly complex. It turns out, though, that version 3.0 or the DOMDocument doesn’t actually use XPath as its default language: it uses a bastardised version of XPath called “XSLPatterns”, which just so happens to not support the substring() function at all.

    So how do we deal with this situation? One way is to always instantiate version 6.0 of the DOMDocument:

    [sourcecode language=’javascript’]xd = new ActiveXObject(‘msxml2.DOMDocument.6.0′)[/sourcecode]

    The problem with this approach is that, like I mentioned earlier, you can’t always be guaranteed that your users will have version 6.0 installed (even though it’s a free download). The safer way to deal with this problem is to switch the expression language to XPath in your 3.0 object:

    [sourcecode language=’javascript’]xd = new ActiveXObject(‘msxml2.DOMDocument’);
    xd.setProperty(“SelectionLanguage”, “XPath”);[/sourcecode]

    The advantage of this approach is that you’re not specifying a version, so when MS eventually changes the default to 7.0 (or whatever), your code will work without a problem.

    For more information on this, check out  this blog post from Microsoft’s XML team, which goes into a little bit more detail.

  • 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.