Archive for the ‘Web development’ Category

Cam****

Friday, May 7th, 2010

What a great day for the United Kingdom of Great Britain and Ireland. I think every man woman and child of this nation will wake this morning with new hope. Hope that the mistakes and missed opportunities of recent years will finally be undone. Hope that, from now on, we will all be armed with a new freedom, a new ease of living our lives without constraint by the petty failings of tired and out-of-date thinking.

I am of course talking about my new website, of which version 1 is now released

ukcampingmap.co.uk

It’s seems like an obvious idea, and I for one can’t believe no-one else has done it yet (particularly as I’ve been ruminating over it for the past two years): All the UK’s campsites plotted on a google map. So much easier than trawling through directories of campsites available elsewhere on the internet, that have only rudimentary or difficult to use tools for finding a campsite in the location you want one.

It has a search (for postcodes, towns, villages, tourist attractions) and also has easy navigation for viewing a single region, county or tourist area (eg Snowdonia).

There’s plenty more work to do on it, but for the first time, after a few weeks of intense work*, I have something fairly stable which is, while still very basic, still a lot easier to use than other campsite directories.

Enjoy.

Oh, and God help us now the  Tories are in!

*well, maybe an hour a day

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;
 };
};

Cooking with SQL

Friday, February 26th, 2010

SQL was the sight of my first forays into programming, back in the days when I managed records for an educational project and came to the heretic conclusion that MS Access was better suited to the task than Excel. But that’s more or less where my learning of SQL stopped, and even then it was limited to SELECT, WHERE and ORDER BY statements (I let Microsoft’s wizards do all the hard work of building multiple table queries).

Fast forward to yesterday and I decided to finally bite the bull by the horns. The back-end of my latest educational endeavour was, I guessed, suffering in speed due to the fact that I made no use of JOIN on my MySQL tables; each time I wanted to get records related to records in another table I would use nested loops in php to get the related records for each row.

In my defence, I largely chose this approach due to another 3 major flaws in  Zend Framework\’s documentation:

  1. It doesn’t explicitly mention that when you build a Zend_Db_Select query based on a Zend_Db_Table class (ie a Model) the FROM clause of the query is automatically filled in. Attempting to fill it in yourself causes an error.
  2. It doesn’t mention anywhere that in order to use JOIN within a Zend_Db_Select query based on a Zend_Db_Table class you need to use the ->setIntegrityCheck(false) method. Without this all manner of confusing errors occur.
  3. This wording: “You can not specify columns from a JOINed tabled to be returned in a row/rowset. Doing so will trigger a PHP error” , coupled with the fact I was getting lots of errors led me to believe that Zend had neglected to add JOIN functionality to its models, so I dropped that line of attack. (In fact, all that quote means is that you cannot change the default behaviour, which is to fetch all columns).

But now I have of course overcome all this, and have managed to eg reduce about 30 lines of code (get a teacher’s classes, then get these classes’ assignments, then get all the attempts at these assignments, and for each of these get the individual puzzle solutions submitted) to a single line using 3 RIGHT JOINs and one INNER JOIN. It’s much neater, and I can only guess at the vast improvements in speed it brings; my guess is “oodles”.

As well as improving my application, learning about Zend_Db_Select (the documentation to this is remarkably well written, considering the surroundings), via the __toString() method, has increased my understanding of the underlying SQL to the point where for the first time I can write non-trivial queries from scratch – eg updating a field based on a join with another table – , which is a great addition to my programming armoury.

Display:run-in – why would you?

Monday, February 22nd, 2010

A while (about 2 years) ago I was reading quirksmode’s page on support for CSS display properties in browsers when I came across a hitherto unknown type of display – display:run-in;

Something with display run-in, if followed by a block level element, becomes the first inline-block of the next block-level element.

So if you have the code

<div style="display:run-in;font-weight:bold;">My run-in box</div>
<div style="display:block">My block box</div>

it should display as follows (though doesn’t in firefox or ie yet):

My run-in box My block box

Quirksmode poses the question: ‘Why would you want to do this?’

Well, I can think of a very good reason: starting a paragraph with a heading, such as the following:

Conclusion: display:run-in can provide a more semantic way of representing a paragraph which has it’s heading as the start of its first line. At present I bet everyone just wraps the heading in <strong> tags, but that’s not really what <strong> is for.

Or also for a definition list

Second argument in favour of display:run-in: Using display run-in, imagine this is a <dt> followed by a <dd>. How would you get the <dt> to appear inline with the <dd> without display:run-in?

So given that display:run-in is useful it’s surprising that firefox are yet to implement it, especially given that ie8 has already done so.

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.

EDIT – There’s a bug that pops up every now and then (something to do with caching) which leads Deletious to show zero bookmarks for your account. I’ll fix the bug when I get time, but waiting a few hours seems to clear the cache (at least, it works for my account) and then you can access your bookmarks again.

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.