Archive for the ‘Javascript’ Category

It’s not what you say, it’s which font you say it in

Wednesday, March 3rd, 2010

I’m redesigning this site at the moment and one thing I wanted to pay closer attention to this time around was choice of fonts. Notwithstanding the fact that web browsers were, until recently, pretty shoddy at allowing you to use the fonts you wanted to, the main reason I hadn’t paid much attention to fonts in the past was that it’s so darn hard picking one, for a number of reasons:

  1. There’s so damn many of them
  2. There’s no relation between names and appearance (as opposed to, say, #f60283 being guessable as a garish pink, closer to red than to mauve)
  3. They’re difficult to preview and compare

So in the interests of productivity, quality and, dare I say it, working smarter, not harder, I’ve devoted some time to sorting out how I choose fonts, reduced to the following four steps:

  1. Organise your fonts in themed folders
  2. Find a good stand alone font previewer i.e. don’t rely on photoshop and windows’ poor tools
  3. Narrow down to a short list
  4. Use javascript to make quick comparisons easy

Read on if your curiosity is piqued.

1. Organising the fonts

Windows’s default font collection (and, I imagine, Apple’s too) and the collection of 2000 fonts I also use are organised alphabetically which is rubbish. Unless you have web design OCD you’re unlikely to want to narrow down your choice of font by it’s first-letter. But, on the other hand, it is difficult to categorise fonts; I’m yet to see a website do it effectively, and I’m not entirely happy with my choice. But in the end I plumped for the following: serif, sans-serif, script, stylised, symbol, stencil.

Stencil could easily fall within stylised, and stylised could easily be split into subfolders (Art Deco, Gothic, Celtic …), and I realised part way through that I should have a subfolder within symbol for fonts depicting alphabets other than Roman, but I think a minimal folder system would be serif, sans-serif and other. In the serif and sans-serif folders I included only sensible fonts you could print a book not aimed at children in, which I think is a useful distinction to make; often the hardest task when picking fonts is to find the one which is subtly different to other ordinary fonts, but somehow suits the design better than almost indistinguishable alternatives. Cutting out all the fancy fonts makes this task a lot easier.

So once you have all these folders put a copy of each font you have in one of them, and you’re ready for the next step. You don’t need to bother with installing them yet.

2. Previewing your fonts

My criteria for a good font-previewer are:

  1. Choice of text to use for the preview
  2. Choice of text-size and colour
  3. Ability to organise fonts how you want them organised
  4. Speed and ease of switching between one font and another
  5. Ease of installing a font

Windows’ control panel fails to meet conditions 1 and 2, and Photoshop’s built-in font selector fails to meet 3 and 4, and they both force you to install a font before using it. The best free solution I’ve come across for Windows which meets all 5 conditions is Fast Font Preview.

3. Short-listing

Once you’ve got Fast Font Preview installed you can start picking your shortlist. Simply browse to your organised font folders, click on settings to type in your sample text, adjust the font-size to what you want, and double click on any contenders. Once the font is opened you can install with one click. While the font is open you’ll also want to jot down its official font name.

4. Use javascript to make comparisons

This is where I stop being pedantic and hopefully can be of some use. Insert the following script into the head of your web-page-in-need-of-a-font, substitute your list of font names and the id/tag name of the elements to be affected and, hey presto, a handy font-switcher should appear, making choosing exactly the right font much easier. If your web page already uses javascript then add the body of the function to your existing onload event. (NOTE: It tends to work better in Google Chrome than other browsers as Google Chrome seems to be a bit more forgiving when it comes to font names).

window.onload = function() {
 var body = document.getElementsByTagName('body')[0];
 var id = '';
 var tagName = '';
 var fonts = 'Comma,separated,list,of font,names';
 fonts = fonts.split(',');
 var elements = (id)      ? [document.getElementById(id)] :
                (tagName) ? document.getElementsByTagName(tagName):
                            [body];
 var switcher = document.createElement('DIV');
 switcher.setAttribute('style','position:absolute;top:0;right:0;background:white;z-index:200;padding:10px;');
 for(var i=0, il = fonts.length;i<il;i++){
   createButton(i);
 }
 body.appendChild(switcher);
 var buttons = switcher.childNodes
 loadFont(0);

 function createButton(pos) {
   var button = document.createElement('a');
   button.innerHTML = fonts[pos];
   button.setAttribute('style','display:block;padding:2px;');
   button.setAttribute('href','#');
   button.onclick = function() {loadFont(pos);};
   switcher.appendChild(button);
 }

 function loadFont(pos) {
   for (var i=0,il=elements.length;i<il;i++)
   {
     elements[i].style.fontFamily = fonts[pos];
   }
   for (var j=0,jl=buttons.length;j<jl;j++) {
     buttons[j].style.backgroundColor='';
   }
   buttons[pos].style.backgroundColor='yellow';
   return false;
 };
};

How I’d teach myself programming, if I could do it all over again

Wednesday, February 17th, 2010

As I mentioned the other day, web development as a career is rare in that you can just pick it up off the internet unlike, say, luxury pet grooming. But it took me a while to find good strategies to learn what I wanted to learn. If I had a time machine I’d go back and tell myself the following*.

Don’t buy beginners guide programming books

I bought a couple of these on php/mysql and javascript. I won’t say they were a complete waste of money as I did learn the basics from them, but there are several good reasons not to rely on them for your starting point:

  1. These books are almost always a long-winded, incomplete version of the programming language’s documentation (which is normally available for free online) structured around building an example application which probably bears little resemblance to something you would like to build, e.g a quiz about the Simpsons
  2. Unlike online resources these books are not searchable with lots of easy to follow cross-references
  3. Online tutorials are more up to date

Find a good online tutorial

For any programming language there will be loads of beginner’s tutorials online; just search Google for “[language name] beginner’s tutorial”. the top results won’t however generally be the best, so open up lots of tutorials in lots of tabs, narrow it down to a few of the best and then bookmark them, before starting to follow one of them. If you get stuck on a section you can always try the explanatiosn given in your other bookmarked tutorials or search google for “[programming language] [topic] explained”. Below are some of my favourite tutorials:

Learn to use documentation

It took me a long time to realise that most programming language documentation follows  the same structure, and once you understand this you are able to teach yourself any language. Roughly, a programming language (at least, the ones I know) is a collection of types of thing (objects, strings, arrays, numbers etc…) and processes (loops, conditionals, functions) for manipulating things, and some things have built in sub-things (properties) and their own dedicated processes (methods), and most processes will only work on certain types of thing (arguments of the correct type).

Well written documentation will list all the above information systematically (together with the basic syntax and rules of the language), so that if you create a variable of a certain type you can find out what you are able to do to it, or if you want to use a function you can find out what conditions its arguments need to meet. An understanding of object oriented programming also goes a long way to being able to grasp documentation, but isn’t essential for a beginner.

Use libraries… lots of libraries

Not the ones with books. A library (sometimes called a framework) is a collection of software written by somebody else that takes care of some tedious/difficult processes for you. The classic example at the moment would have to be jQuery. Without jQuery the differences between browsers’ implementations of javascript would make developing javascript web applications a specialised and difficult task with unreliable results. Because jQuery is a collection of code that thinks about all the cross-browser differences for you (as well as doing lots of other useful tasks) creating reliable javascript applications is now something even beginners can take on. Some libraries also have thriving communities that build plug-ins to extend the functionality further.

And to make use of all this all you have to do is include a file (or collection of files) and get to grips with the library’s documentation (often called an API – Application Programming Interface) which, no matter how daunting it may seem at first, is guaranteed to be easier than writing all the code yourself.

Invest in some expert/advanced books

Beginner’s guides may have been made redundant by the internet, but there is still room for more advanced books. Yes, the information is probably on the internet somewhere but structured tutorials aimed at more advanced users are far less common than beginner’s tutorials. I won’t recommend any books myself as I don’t consider myself enough of an expert to judge, and I also don’t own many yet, but the ones I do have are full of techniques I couldn’t have worked out for myself.

And that’s how I should have done it!

*Like hell I would. Straight to the bookies it’d be.

Remove text nodes function

Wednesday, February 17th, 2010

Here’s a fairly useful function for when you’re using javascript in a web page without using  library like jQuery to take care of the nitty gritty.

It tackles problems that occur when you get the child nodes (eg myList.childNodes) of a DOM node, but there is whitespace in the html. Each of these whitespaces gets counted as a DOM node of its own, a text node, so if you run code to iterate through eg all the children of a <ul> you will find that your code throws an error as not every node is an <li> as you expected.

function removeTextNodes(nodeList) {
  list = Array.prototype.slice.apply(nodeList);
  for(var i=0, il=list.length;i<il;i++)
  {
    if(list[i].nodeType == 3)
    {
      list.splice(i,1);
      i--;
      il--;
    }
  }
  return list;
}

var myUL = document.getElementById('myUl');
var myLIs = removeTextNodes(myUL.childNodes);

I haven’t tested it in any browsers apart from firefox as I’m a bit busy, but if you find it’s buggy in Internet Explorer or elsewhere leave a comment.

(By the way, if you’re wondering about eth relevance of the image, if you search for “too many children” in flickr it throws up lots of photos of a very serious looking texas school board meeting. Too many children in Texas, apparently!).

Deletious

Sunday, February 14th, 2010

Well, this has to be the quickest I’ve ever gone from idea to publishable (albeit limited functionality) website.

Deletious is my new site for simultaneously viewing a page bookmarked in Delicious and deciding whether to keep or delete the bookmark. I’ve had quite a lot of fun using it the last few days, rediscovering all sorts of articles, games, tools and other long forgotten sites. As well as wasting a lot of time reacquainting myself with all these I’ve also managed to de-clutter my Delicious account; all the CSS articles from 2-3 years ago giving an introduction to topics I now know inside out are gone from my bookmarks, as are all those gimmicky websites I can’t believe i found funny at one time.

Disappointingly, I’m having problems uploading the logo to the website’s folder, but it’ll be sorted sometime soon I hope.

So please do give it a go and let me know what you think.

Delicious, though not so easy to swallow

Thursday, February 11th, 2010

For a long time I’ve wanted to work with the Delicious API. Initially it was because the Delicious website not only had the difficult to remember del.icio.us url, but was also very badly designed. If you compared its progress – addition of new features, cleaning up of design, making use of new techniques suchas AJAX – with its web2.0 compatriots (Flickr, Digg, boris-johnson.com) it lagged way behind.

So I initially planned to build a new front-end for it, making it easier to work with your bookmarks, but before I could progress far enough in my coding abilities they completely redesigned the site; a vast improvement.

Though still not perfect. For a while I’ve found it frustrating that there is no easy way to simultaneously see the content of a bookmarked page and delete the bookmark if you deem it no longer useful, so my delicious account gradually got more and more cluttered. Well, this afternoon I decided to do something about it (and not just because I’m avoiding doing more important stuff).

But I was foiled for a long time by the laziness of the Delicious developers. My initial plan was to use javascript to get a JSON of all my bookmarks (or alternatively request one at a time) and go through them one by one, displaying the webpage in an iframe, and offering the option to discard or keep the bookmark. However, delicious only publish this data as XML which means, due to cross-domain restrictions on AJAX, you can’t just use javascript. I may be a bit hasty in pinning this on developer laziness, but I imagine creating alternate templates (because that’s all the difference between JSON and XML really) wouldn’t be too time consuming, and would greatly enhance the versatility of the API.

Anyway, I realised I would have to use a bit of PHP to get the XML and create pages from which my javascript would be able to access the data. Luckily, before I dived straight in I came across phpdelicious (which, appropriately, I have now bookmarked in Delicious) , a very easy to use php class for wrapping the Delicious API, which is very handy indeed. Less than an hour later I had built exactly what I wanted.

I reckon a few more hours development and I can make it a publicly available service.  All I need to do is include a form for other users to be able to login, and (ideally) preload websites in the iframe to speed things up (though this is problematic as some sites force the whole web page to be redirect if you try and put them in an iframe).

Sorted

Tuesday, February 9th, 2010

One of the problems I had to solve when writing my new jQuery listSplitter plugin was sorting an array of arrays/multidimensional array by one given column, eg

testArray = [[a, b], [b, a]];

How would you sort by the second column of the array?

I’m not sure if mine is the best solution, but here it is (it also works for an array of objects as well as an array of arrays):

/**
* sorts an array of arrays or objects using a specified column/property
*
* @param column (str/int) - the name/index of the column to use for sorting
* @param sortFunction (func) - the sort function to use for sorting (sort functions
*                             that can be used by array.sort() will also work here)
* @return array
*/
Array.prototype.sortByColumn = function(column, sortFunction) {
  return this.sort(function(a,b) {
    var testArray = [a[column], b[column]];
    testArray = (sortFunction) ? testArray.sort(sortFunction) : testArray.sort();
    return (testArray[0] == a[column]) ? -1 : 1;
  });
}

And to apply it to an array use it similarly to the array.sort() method, eg

myArray.sortByColumn(5);//sort alphabetically by column 5 of the array
myArray.sortByColumn('title', sortByLength); //sort by length of title attribute
function sortByLength(a,b) {
   return a.length - b.length;
}
myArray.sortByColumn('price',function(a,b){return a - b}); // sort by price

How it works

It runs the normal array.sort() method, but uses as its sort function a clever little function which picks out the values to be sorted by, creates a new test array out of these values and sorts it. Using the ternary operator, it checks if the test array is unchanged after this sort. If it is unchanged it means that the items in the original array are already in the right order so no change is made, otherwise they are swapped in the original array too.

jQuery listSplitter plugin

Monday, February 1st, 2010

A very short post to announce my third  jQuery plugin: listSplitter, which takes a long list of categorised items (where the categories can overlap) and creates a tabbed interface to show only one category at once. I haven’t done a demo yet (well, I have, buthaving teh same old problem transferring to the server as the server runs on UNIX while my laptop is Windows. I recently found out why this causes a problem, but no easy fix has presented itself) so you’ll just half to take my word for it, though before too many months have gone by I will use it as the basis for a new portfolio.

*edit: Here is a demo

And it can be used with jQuery themeroller, i.e. use the tool at jqueryui.com/themeroller, to design how it shoudl look, then after clicking “download theme” make sure you have ‘tabs’ ticked underneath widgets.

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

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)