Archive for the ‘Web development’ Category

Probably the best example of the sort of stuff I’d do

Thursday, January 28th, 2010

This blog is meant to do two things:

  1. Let the world know that I’m a decent front-end web developer
  2. Be the focus for a new doomsday cult

Number two is progressing nicely as no-one has gotten wise to my subliminal messages yet, but what of number one?

Let’s evaluate:

  • Design – it’s not finished yet (and never will be as I will hopefully do a redesign next month when I have a bit more time), which doesn’t look so good
  • Javascript, CSS, HTML – apart from mentioning the odd bug/annoyance there’s very little to show what I can do with these… aside from my jQuery plugins which hardly have pride of place either

Over the last few months I’ve come across a few blogs which, unlike mine, really cut the mustard when it comes to being an extended portfolio, putting mine to shame.

jasonsantamaria.com and dustincurtis.com are a little bit twitter generation for my liking, but one can’t deny that their blogs, where every article has a different design, are great examples of showing off on your blog.

But my favourite, which I came across today, has got to be www.romancortes.com. Most of his most recent posts feature him achieving visual effects which simply have to involve Flash… only they don’t, and in many cases achieve quite striking results without even using javascript; just pure CSS/HTML. As he himself admits, most of the demos aren’t much use in a practical website, but they’re still pretty impressive in showing what surprising visual effects can be achieved, and figuring out how he did them is quite a good test of your understanding of CSS. My favourites are the coke can and the old master.

Obviously, when you see that someone has managed to animate a rolling coke can using just one static image of a coke can label and some CSS, and after the initial wow has subsided, a Peep Show quote springs to mind:

Super Hans: I think this is probably the best example of the sort of stuff we’d do we’ve ever had.
Jez: Oh yeah. ’cause sometimes it’s really hard actually to do your own ideas

Do I have it in me to produce a more stunning showcase of what I can do? Who knows, but having just learned The Mason’s Apron on guitar I feel invincible!!!

Immunodeficiency

Tuesday, January 26th, 2010

I just solved  a bug which stemmed from the fact I forgot that javascript is a referential language, i.e. if you have a variable and you set another variable equal to it then it doesn’t in general clone the original variable, but merely just points both variables towards the same underlying object. This only applies to Arrays and Objects though, and to prove it here is a little demo (it turns out you can embed javascript straight into wordpress posts now!)

Irritatingly, if you have a bug which is caused by forgetting this principle then this will also make it hard to debug because it also affects how firebug reports information to you. When you console.log() an object or an array, firebug does the same as javascript – it creates a reference to an underlying object in the DOM. So, if you’ve been logging an object repeatedly in order to pinpoint when a rogue change takes place firebug will consistently provide you with references to the object as it is after your script’s finished running – not much use.

However, there is an easy way out*. console has methods other than .log(), and possibly the most useful is console.dir(). console.dir() takes a snapshot of any object or array, printing out each of its properties without maintaining a reference to the underlying object, and therefore giving a you a snapshot of an object as it is at the time.

*And a hard way (console.log() the properties of an object individually), which is how I resolved my bug, before  looked into what other methods console had

Facebook fail to make it easy for people not to embarrass themselves

Thursday, December 17th, 2009

Head in hands

My attitude to Facebook has always been that it is a useful address book of sorts (with built in slideshows), and that all these scandals where people get fired from their jobs for posting on facebook pictures of themselves disfiguring a company business card with a nail file are their own fault for showing a lack of discretion.

That said, though, Facebook do have a reputation (fairly well-earned if you ask me) for not making it clear to people who they will share things with, but now they’re putting it right as when you login you are nagged to confirm you old privacy settings or change them to new ones, just so everybody’s clear what to expect.

Heres’ the form you fill in, which looks pretty simple – radio buttons to indicate yes or no… or so you would think. But regretably facebook have ballsed up their privacy issues again.

For each element of facebook you can set it’s visibility level to either what you’ve already got it set to, or one of Everyone, Friends of friends or Friends… but for each bit of Facebook you don’t get to choose from that list; you are presented with one of them as an alternative to your current settings (picture).  Now, that’s a pretty confusing start, because

  1. It makes the layout of the form all weird: the radio box in the first column doesn’t always mean the same thing, which users come to expect from columns of radio buttons.
  2. Some elements have “Old settings” checked, and others have the other radio button checked, which confuses the whole idea of you changing your own settings
  3. When you arrive at the page there is nothing to tell you what your old settings are. I’m sure many users will go straight from here to check in their account what their settings are.

But on hovering over an old settings checkbox it displays a tooltip to tell you what those settings are, which si helpful , yes, but nowhere near as helpful as just including it in the original page’s text. Horrible overuse of technology.

So does the confusion end there?

Of course not.

Below are three examples where it doesn’t allow you to do what you want, or just gets more confusing

Facebook settings detail

  1. I can choose to allow everyone to read About me or just friends. It doesn’t allow me to let Friends of friends see this
  2. At the moment ‘Only Friends; Except: Limited Profile” can see photos and videos of me, but it’s taken me a while to remember what “Limited Profile” means, and now that I do remember, why is this not an option for …
  3. … sharing my email address, which I’m more likely to be cagey about. And it would also be nice to have radio buttons which allow me a wider choice than sharing my email address with “Friends” or “Only Friends”

It amazes me how sloppy supposed beacons of the internet can be sometimes.

A List Apart survey

A greasy framework

Monday, December 14th, 2009

As I think I may have mentioned, the latest project I worked on I’ve been using the Zend Framework for all the server-side development. Over the last few months I’ve developed a love hate relationship with it. On the plus side it does pretty much everything I need without needing too much customisation, a few of the negatives though are:

  • The quickstart in the documentation assumes way too much background information about configuration of a php app and data sources etc. They don’t seem to have considered that a reason many programmers use zend is because they don’t know too much about back-end development and want something to take care of the tricky bits for them. It took ages to get past this stumbling block, with the help of this tutorial (WARNING: The bit on connecting to the database either uses quotes when it shouldn’t or vice versa) and this website with tutorials on various zend components.
  • Having said it does everything, there are lots of gaps. I’m sure a lot of thought goes into deciding what gets included and they must get all sorts of requests, but some simple standard things are missing, eg a validator to check a confirm password field. Nevertheless it is fairly easy to write extensions, but the zend documentation site should have a lot more and clearer information on this. Linked to this, there seems to have been very little thought put into building some sort of community to share plugins, unlike jQuery, for example.
  • You may have sensed that I don’t have a great deal of respect for the documentation. It’s very sloppy to be frank. There are so few cross-links to different sections, and a lot of the classes contain examples which I found fairly irrelevant, covering a way of doing things unlikely to be used in a real website (eg the examples for querying your database don’t really use the Model-View-Controller structure you’re supposed to use). And, in my view, it’s way too wordy, and much of the text is just waffley clutter; far more so than better examples of documentation, such as php and google maps. The website is also very difficult to navigate.

To fix the final gripe I’ve written a greasemonkey script (my first ever one) to replace the existing documentation layout with one a little easier to negotiate.

Before greasemonkey

Before greasemonkey

Before greasemonkey

After greasemonkey

Wide open space

Friday, December 11th, 2009
Not a LOL cat

Not a LOL cat

My laptop (now on its very last legs) has a fairly dinky screen. It’s wide enough to not be a problem, but the height is always a pain, especially that now (unlike when I bought the laptop all of 4 years ago) I am a web developer and routinely have firebug and the web developer toolbar open, which sucks up about two fifths of the height of my screen.

Enough is enough, and I’ve decided to get tough on undesirable widescreen, tough on the causes of undesirable widescreen.

First off, although I don’t like Google Chrome’s tabs at the top interface, I do like the fact that they’ve squeezed something useful onto the otherwise desolate windows title bar, i.e the bar at the top of the screen that tells you which program you’re using and, in firefox, the webpage’s title. As I have no need for firefox to tell me anywhere other than on the tab which web page I’m on, this bar is pretty much useless. And, luckily for me, there is a new firefox extension to get rid of it: Hide Caption. It shifts the close, maximise and minimise buttons down to near the search bar and gives me an extra cm of space. It warns that it may not be compatible with tab-mix plus, though I haven’t had any problems, and I use loads of other extensions too with no clash. Although I did uninstall another plug-in called Hide Navigation Bar as this didn’t work, but it may have been a clash.

A few of other things I’ve done to save space and decrease clutter is decrease the text size in firebug, change my windows taskbar to a single row rather than two, use the personal menu extension to hide the menu bar, and got rid of my bookmarks toolbar (although not sure how long that will last). It would be really handy if firebug could have an option to place it to the side of the screen rather than the bottom. Most of the time the lines don’t span the width of the console, so it’d be a great space saver to stack them vertically down a narrow strip at the side of the page.

Incidentally, one of the few add-ons that has remained a constant for me over the years is the qute theme. It’s really nicely designed with light colours and small icons and makes the screen seem a lot less cluttered. There’s two versions available at the moment; the authentic new version for firefox 3.5, and the retro version based on the original icon designs from years ago, which is the one I plump for. Aside from being aesthetically more pleasing it also has the advantage of not having a heart as the icon for bookmarks, which always took me a second to work out what it meant.

Anyway, here is my current, much cleaner looking, firefox appearance now (I would do a before and after, but it’s way too much hassle to go back and disable all the things I’ve changed):

Slimline firefox

Well I never

Thursday, December 10th, 2009
Colouring in

Colouring in

If there’s one thing I know when it comes to web development, it’s CSS. I don’t always write it in the most organised fashion (though I like to think I do when I’m given a finished design to work from), but for over a year now I’ve felt that my knowledge about the bits of CSS that I use daily is pretty complete*. And for the bits I don’t have to use very often I an always find what I need on the internet.

So imagine my surprise today when I realised that there’s one area of CSS that I use everyday with a fetaure I was completely unaware of. I’d always thought that

p{color:red}

meant “Make the text in the paragraph red”, but it turns out that that’s not the full story.

In all browsers, it seems, if border-width and border-style are defined for an element, but no border-color, then color also defines the border colour. But then if you define a value for border-color then color gets ignored when calculating the border colour. Even if you use another selector of higher specicifity to set a new value for color this still has no effect on the border colour. Here is a demo page.

But is it of any use?

Well, yes – it turns out it is.

Let’s say you want to define a generic button item as follows

.button {display:inline-block;border-width:2px;border-style:solid}

Then you can coordinate the text and border colour of the buttons by just using, eg

.cancel {color:red}

And this technique could be used for all sorts of generic elements where text colour and border colour are normally same. To use a different colour for the border it’s an easy thing to over-ride too.

Has anyone ever included both the British an d American spellings of colour this much in one article before?

* excluding newly emerging vendor-specific styles, eg -webkit-make-it-look-cool {}

Ternary gets a turn

Thursday, December 3rd, 2009

I’ve recently started using the ternary operator more. For those not in the know already, it’s a bit like shorthand for

if () {
} else {
}

but with a few similarities to other parts of the language too (NB this is based on the javascript implementation – other languages may differ slightly).

So, in the simplest case, instead of writing

if (statement)
{
   codeblock1
} else {
   codeblock2
}

we can write

(statement) ? codeblock1 : codeblock2 ;

which is a great way of cutting down on lines of code when each code block is only a single line. A few tricks to make using it more fulfilling are as follows.

The ternary operator can be split over two lines

So instead of

(statement) ? codeline1 : codeline2 ;

I mostly use

(statement) ? codeline1 :
              codeline2 ;

I find it more readable, as it really draws out the structure of what the code is doing. It also looks a bit like a switch statement (which, incidentally, I hear runs slow in javascript), which will come in useful later.

You can get rid of the brackets/parentheses

I tend to leave them in though as if the statement to be queried is long it would otherwise be easy to not notice that at the end of it comes a ?. The brackets remind you that what’s within is to be evaluated as true or false.

The ternary operator doesn’t have to start the line, and often shouldn’t

The following lines are equivalent:

(cetacean.mass > 1000) ? var family = 'whale' : var family = 'dolphin';
var family = (cetacean.mass > 1000) ? 'whale' : 'dolphin';

As you can see the second version results in less code, which is also easier to comprehend as the action of the line – assigning a value to a variable – is clear from the beginning of the line. As a rule of the thumb I put as little within the ternary operator as possible.

(As an aside the && and || operators – normally seen within if statements – can also be employed, using similar syntax, to assign values to variables. This is why I don’t think it’s fair to say that the ternary operator is just shorthand for if … else …, as it bears similarities to other bits of the language too. )

Sometimes the ternary operator can’t start the line

The only example I’ve come across so far is

return (cetacean.mass > 1000) ? 'whale' : 'dolphin';

Putting the return after the statement to be queried causes an error.

The ternary operator can be nested to emulate ‘else if’

First of all

if(statement1) {
  code1
} else if (statement2) {
  code2
} else if (statement3) {
  code3
} else {
  code4
}

Can be rewritten as

if(statement1) {
  code1
} else {
  if (statement2) {
    code2
  } else {
    if (statement3) {
      code3
    } else {
      code4
    }
  }
}

and so on for more statements.

But we know ifs can be rewritten using ternary, so it’s also equivalent to:

(statement1) ? code1: ((statement2) ?  code2 :( (statement3):?code3: code4));

which can unbelievably be rewritten on more lines as

(statement1) ? code1 :
(statement2) ? code2 :
(statement3):? code3 :
               code4 ;

So now you can construct very concise, relatively fast and, in my humble opinion, readable if … else …/switch statements. This is particularly valuable for defning  the value of a variable quickly, and based on a variety of conditions, eg:

var family = (cetacean.mass > 1000)             ? 'whale' :
             (cetacean.noseshape == 'cylinder') ? 'dolphin':
                                                  'porpoise';

Neat!

This literally changes

Monday, November 30th, 2009

You should know that I’ve built up a lot of half-written posts recently, mostly about javascript, so this blog, as it emerges from semi-hibernation, is gonna get code-ier and more out of date as I work backwards.

So to begin at the end, I recently came across a bug which is far from obvious to track down. Look at the code below.

var MyClass = function() {
  this.a = 'dolphin';
  this.getA = function() {
    return this.a;
  }
}

myObject = new MyClass();
var callbacks = {callback1: myObject.getA}
newA = callbacks.callback1();

What will the value of newA be?

In my application, in which I used callbacks to store the callback functions for a series of custom-made dialog boxes, I was expecting the value to be a, but it isn’t. The reason for this is that callbacks is an object, and saving a function as a property of an object is, in effect, creating a method of that object, and methods of objects, when called using the ‘.’ syntax, will tend to have this refer to the object (not always, but normally). So in creating the callbacks object you inadvertently cause getA to fail as this no longer points to the myObject object, but to the callbacks object literal.

Fair enough. But what makes this error particularly difficult to track down is that firebug shows console.log(callbacks) to be an empty object. Why this is, I don’t know – it seems unlikely to me that the properties wouldn’t be created due to the value of this being reassigned, so maybe it’s a mistake in firebug ( a firebug-bug, if you will). A similar error occurs when using an array as callbacks instead of an object, but firebug reports that the function is stored in the array, and that it returns an undefined value, so it’s a lot easier to see what the problem is. But once the bug is found, the workaround for the array and the object is the same.

The method I’ve chosen is to define

var that = this;

at the top of the MyClass function, and anytime you use this but think it may be called in such a way that the context may change, substitute that for this. But this is far from perfect – you have to second guess when you will need to do this as it’s not always obvious, and you could easily miss an instance which doesn’t occur very often, but which is fatal when it does. Another solution is to use the prototype.apply method to explicitly set the context of the method, though it looks ugly and a bit indecipherable. On the other hand it is a lot more bulletproof.

I’m sure you’ll make the right decision.

(More sponge creature fun here)

But it works for me!!!

Monday, November 16th, 2009

The lines of javascript below, included at the top of your scripts, could save you a lifetime of confusing conversations with clients where they say an application doesn’t work and you can clearly see that it works on your laptop.

The difference is that you have firebug installed and they don’t, so for you console is defined, but for them it is not, so if you leave any references to it in the app it will throw an error for them. But this fixes that;

if(!console) {
 var console = {};
 console.log = function() {
   return null;
 };
}

A useful debugging method

Friday, October 30th, 2009

I’m always dismayed by the lack of debugging information out there. Yes, there is plenty of information on how to fix particular bugs, but very little on the more general heuristic processes for finding the source of a bug. This may be because debugging is, by its very nature, a thankless process of trial and error.

But nevertheless, I’ve just discovered for myself (though it may be common practice for others already) a technique for debugging when the bug lies within a function which runs numerous times without fail, but when fired on another particular occasion, fails. For example, you have one function which creates shopping basket items from all your user’s saved data at startup, but when you try and use the same function later to create another item based on user input, the function fails.

Putting some var_dump() [php] or console.log() [javascript] calls inside the function will result in reams of information being printed out, most of it useless as its produced by the successfully running first calls to the function. So what I now do is this:

Change

function myFunction(param1, param2, ..., paramN) {
    some = code;
    console.log(something);
    some = more(code);
}

to

myFunction(param1, param2, ..., paramN, test) {
    var some = code;
    if(test) {
        console.log(something);
    }
     some = more(code);
}

And change the function call that needs debugging from

myFunction(a, b, ... N)

to

myFunction(a, b, ... N, true)

Now you will only be shown the debugging messages when you need them. It’s particularly useful for javascript as the console area of firebug is so small so its good to limit messages to only those which are relevant.