Web Design & Development Blog
RSS Feed
Subscribe to my
RSS feed

The Web Design & Development Blog is written, coded and maintained by Duncan Midwinter. It regularly features articles on HTML, CSS, Javascript, PHP, Web Design and more…

Posts for tag: web development 19

A useful little hack for anyone who still uses CSSEdit

Yes I know, CSSEdit has long since been discontinued. But if like me you still prefer it to anything else for coding ‘vanilla’ CSS you may like this little hack for enabling the Safari Web Inspector in the app.

Open Terminal.app /Applications/Utilities/Terminal.app, and copy and paste the following…

defaults write com.macrabbit.CSSEdit WebKitDeveloperExtras TRUE

…then press return.

You should now be able to right click in the preview window and select ‘Inspect Element’ from the contextual menu to open the Web Inspector.

opening the web inspector in cssedit

Don’t like it?

defaults write com.macrabbit.CSSEdit WebKitDeveloperExtras FALSE

To put it back to how it was before.

ResponsiveResize – a Safari Extension to help with responsive design

Responsive ResizeThe ResponsiveResize extension for Safari help speed up development of responsive design by automatically re-sizing the Safari viewport with pixel precision to one of several preset widths. In each case the space taken up by the scroll bar is accounted for. If the particular width you want to work to is not one of the preset values there is also in input field to type your required viewport width.

Basically I’ve been working on some responsive site designs recently (including a ‘soon to be completed’ re-design of this site) and I was annoyed to discover that the Safari window can’t be resized smaller than 376px – no good if you want to check your design at 230px!. After a bit of experimentation I found out you can take it right down to 84px if you do it programmatically, and so the ReponsiveResize extension was born.

Responsive Resize Safari Extension

Most of the presets cover iPhone (230px by 480px) & iPad (768px by 1024px) as these were the target for the sites in question.

The style of the extension toolbar borrows the ‘iOS’ theme from my ButtonBar+ multiple bookmark bar extension.

You can download the ResponsiveResize Safari Extension from my downloads page.

How to add CSS3 properties to CSSEdit

For better or for worse CSSEdit was discontinued when MacRabbit released Espresso 2. I’m sure I wasn’t the only one eagerly awaiting CSSEdit version 3 with CSS3 capabilities but unfortunately it never came — or rather it came incorporated in to Espresso and was discontinued as a stand-alone app.

CSSEdit can be made to support CSS3Well, I tried Espresso but it doesn’t really suit my workflow and so I continue to use CSSEdit 2.6.1. However, there is a way CSSEdit can be hacked to get some CSS3 goodness in there…

If like me you are using CSSEdit on a daily basis you’ve probably long since abandoned the Visual Editor (GUI) panel for most things and work solely in the Source Editor panel. Typing with auto-completion is what makes CSSEdit so fast and easy to use and it’s exactly here that we can add our CSS3 properties and values.

CSSEdit - show package contentsFirst of all open your apps folder, locate CSSEdit and control-click on the icon. Then select ‘Show Package Contents’ from the contextual menu and open the ‘Contents’ folder. Inside the ‘Contents’ folder, locate and open the ‘Resources’ folder and then locate the file ‘AutoCompletion.plist’. Rename it (or move it somewhere else), then download the following replacement .plist file:

CSS3 properties for CSSEdit: https://gist.github.com/2272849

Put the new AutoCompletion.plist file in to the ‘Resources’ folder and re-start CSSEdit. Now when you type you should find that you have all CSS3 properties and values available. I’ve also included various vendor specific properties and a few useful extras.

CSSEdit with auto-completion for all CSS3 properties and valuesNote: Many of the properties in the full CSS3 spec are not currently implemented in any browser. If you want to exclude anything, simply locate it in the .plist file and comment it out using standard html comments eg:


If you are a CSSEdit user I hope you find it useful – I find it has really speeded things up for me!

Oops! Just amended a small typo – the extras section includes the ‘behavior’ property which I accidentally spelt the British English way 😉 12/04/2012

CSS3 tables with rounded corners and css selectors

css3 table with rounded cornersI recently had to style a table for a shopping cart with rounded corners and a drop shadow. So how is this done? It would be great if you could just slap “border-radius: x” straight on to the <table> element and it would be done but unfortunately this doesn’t work. You have to get a rounded corner on to each <th> or <td> at the corners of the table.

So how do you do that? Add a class to each corner cell? I suppose you could but it would mean ugly html. CSS to the rescue! By using child selectors you can get those round corners in there without touching the html at all…

For example: to target the top left-hand cell (assuming you have a header on your table), you target th:first-child (the first <th> element); likewise to get the top right-hand cell you target th:last-child.

To get the bottom left-hand cell you need to target the first cell of the last row of the table. In this case, your selector will be: tr:last-child td:first-child

…and for the final corner: tr:last-child td:last-child

Finally, the zebra striping on the table is done using the :nth-child selector: tr:nth-child(even) will select only the even numbered rows (note: in the following example I have used tr:nth-child(even) td as I am using gradients (the gradients need to be on the <td> element else they stick out of the rounded corner in Firefox).

Here’s a live example of my CSS3 tables with rounded corners on dabblet.com

The html markup for the table was generated using my own Create Table plugin for Coda.

Create your own .SVG graphics with the new SVGedit Safari Extension

SVGedit Safari Extension icon

The SVGedit Safari Extension works like a mini vector drawing app, enabling you to create and save SVG (scaleable vector graphic) and PNG images. Once installed it puts a small pencil icon on the main Safari toolbar. Clicking the icon opens the SVG-edit application which has most of the familiar vector app tools and features. From here you can design your graphics, and save them as SVG of PNG.

The SVGedit Safari Extension

The SVGedit Safari Extension has been created using SVG-edit v1.5.2. You can download it now from my Software page →

Ad campaign tracking with Magento

Ad campaign tracking with the Magento e-commerce system

I’m going to show you how to track ad campaigns in Magento to find out how many orders they are generating.

Imagine you have an ad campaign running on Facebook for your Magento store and you want to know how many of those clicks are being converted in to orders. The way to achieve this is to set a cookie for all visitors who arrive to your site via Facebook. If you give each cookie generated a unique id and then store the data in a database, you will be able to track each visitor if they then return within a given period and place an order in your store. To do this you will need to add a new table to your Magento database, add a few new files, and edit a few files…

1 First up, you will need to check your theme for the following files:


Don’t worry if they don’t exist in your theme. If you don’t have them, simply copy them in to your theme from the following locations:


Now, you will be able to modify these files without disturbing your installation of Magento.

2 Now, you will need to create a new template file for your ‘success’ page. The ‘success’ page is the page that you are sent to after completing an order. Don’t worry, this is not complicated — it’s just a case of duplicating the template file that you are currently using for the checkout process, and giving it a new name. In my case I am using a template file called ‘2columns-left.phtml’, so I duplicate it and rename it ‘2columns-left-success.phtml’.

The template files for your theme are located here:


3 Now, to get Magento to use your new template for the ‘success’ page, you will need to edit the ‘checkout.xml’ file that you copied in to your theme in stage 1.

Open it, and locate the following line (line 412):

<action method="setTemplate"><template>page/2columns-left.phtml</template></action>

Edit it to use your newly created template file:

<action method="setTemplate"><template>page/2columns-left-success.phtml</template></action>

4 OK, now it’s time to work on the database to store your tracking data. You need to create a new table in your Magento database called ‘tracking’ with the following structure:

| Field     | Type          | Null | Key | Default | Extra |
| id        | varchar(16)   | NO   |     | NULL    |       |
| source    | varchar(60)   | YES  |     | NULL    |       |
| time      | datetime      | YES  |     | NULL    |       |
| sale      | enum('0','1') | NO   |     | 0       |       |
| sale_time | datetime      | YES  |     | NULL    |       |
| order_id  | varchar(50)   | YES  |     | NULL    |       |

You will be storing the following data:

  • id – this will be a random 16 chr string that will be used as the name of each cookie created.
  • source – this will be the value of the cookie, and will contain the domain of the referring site.
  • time – this will contain the date and time of the cookie’s creation.
  • sale – a simple boolean, 0 if no purchase, 1 if a purchase is made before the cookie expires.
  • sale_time – if a purchase is made, this field will contain the date and time of the purchase.
  • order_id – finally, if a purchase is made, this field will contain the corresponding order number.

Here’s the SQL to create the table:

CREATE TABLE `tracking` (
  `id` varchar(16) NOT NULL,
  `source` varchar(60) DEFAULT NULL,
  `time` datetime DEFAULT NULL,
  `sale` enum('0','1') NOT NULL DEFAULT '0',
  `sale_time` datetime DEFAULT NULL,
  `order_id` varchar(50) DEFAULT NULL

5 Now that you have the database set up it’s time to start adding the necessary code. Firstly, in the root level of your Magento site, create a new file named ‘cookie_settings.php’.

Add the following php to this file and save it:


## add all domains you wish to track to this array ##

$cookie_arr[0] = "www.google.com";
$cookie_arr[1] = "anet.tradedoubler.com";
$cookie_arr[2] = "www.facebook.com";

## cookie parameters ##

$number_of_days = 30;

$cookie_path = '/';

$cookie_domain = '.yourdomain.com';


This pretty much speaks for it’s self.

Add any domains you want to track to the $cookie_arr array.
Set $number_of_days to the amount of days you want each tracking cookie to last for.
Leave $cookie_path as is.
Set $cookie_domain to the name of your domain (careful, don’t omit that leading full stop).

6 The landing page code. Open the template that is used for your landing page, and add the following code to the top of the template, the comments in the file pretty much sum it up:

//random string function (source: http://www.lateralcode.com/creating-a-random-string-with-php/)
function rand_string( $length ) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	
		$size = strlen( $chars );
		for( $i = 0; $i < $length; $i++ ) {
			$str .= $chars[ rand( 0, $size - 1 ) ];
		return $str;

//get the cookie settings...
require_once( 'cookie_settings.php' );

//get the refering url and parse it...


//if the referring url is in the list...
if(in_array($source,$cookie_arr)) {
    	//if it is a valid source, set a cookie...
	//set the name of the cookie as a random string of 16 chars...	
 	setcookie( $source, $identifier, $date_of_expiry, $cookie_path, $cookie_domain );
 	//register the information in the database...
 	$write = Mage::getSingleton('core/resource')->getConnection('core_write');
 	$write->query("insert into tracking (id, source, time, sale) values ('$identifier', '$source', NOW(), '0')");


CREDIT: the random string function comes from: http://www.lateralcode.com/creating-a-random-string-with-php/

7 OK, that’s the landing page dealt with — now it’s time to add the code to the success page. Open the ‘success.phtml’ file that you copied in to your theme in stage 1, then add the following php to the top of the file and save it:


//get the cookie settings...
require_once( 'cookie_settings.php' );

//loop through the process for each domain being tracked
foreach($cookie_arr as $value) {
	//if a valid cookie is set when we get to the success page...
	if(isset($_COOKIE[$value])) {
		//get the value...
		//update the database entry...
	 	$write = Mage::getSingleton('core/resource')->getConnection('core_write');
	 	$write->query("update tracking set sale='1', sale_time=NOW(), order_id='$order_id' where id='$cookie_value'");
	 	//delete the cookie...
	 	setcookie($value, '', 1 ,$cookie_path, $cookie_domain);



Once again, the comments sum it up.


OK, so now your done — each time a visitor lands on a product page from one of the sites you have specified in the cookie_settings.php file, a cookie will be created and recorded in the database. Should that visitor then make a purchase within the time limit specified in the cookie_settings.php file, the record will be updated to contain the purchase time and order number and the cookie will be deleted!

You can download the code from this post here: Magento Ad Tracking

P.S. in this particular setup, any page using the 2columns-left.phtml template functions as a landing page. If you wish to limit the landing page to 1 specific product. Simply create a new template file, perhaps 2columns-left-landing.phtml containing the landing page code, and specify that template for the chosen product in the Magento Backend (In this case DON’T add the landing page code to the normal 2columns-left.phtml file). If you follow this route, you will need to reference the new template in the following file to make it useable in the Magento Backend:


locate the <layouts> and add the following:

<two_columns_landing module="page" translate="label">
	<label>2 columns landing page</label>

Introducing Text Tools – a simple text manipulating Plugin for Coda on the Mac

Coda Plugin - Text Tools

I recently released my first Plugin for Coda (Un-Encode Entities), now follow on from that I have created another: Text Tools.

The Text Tools Plugin for Coda adds several options for quickly manipulating text in your html / php / javascript etc… files. The options it adds are as follows:

  • Convert to UPPERCASE
  • Convert to lowercase
  • Convert to Caps Case
  • Newline to <br />
  • Add Slashes to Quotes
  • Strip Slashes from Quotes

Text Tools Plugin for Coda

You can download the Text Tools Plugin from my Downloads page. (Requires Coda for Mac OSX).

Un-Encode Entities: a plugin for Coda

Coda Plugin - Un-Encode Entities

I’ve been using Coda on the Mac since it first came out (2007 I think), and well, I’ve just discovered how simple it is to create plugins using nothing more complicated than PHP. So here it is: Un-Encode Entities, a Plugin for Coda.

It works like this. Basically if you have something like this:

&lt;blockquote&gt;&lt;p&gt;&#8220;Arte non &egrave; mai finita, &egrave; solo abbandonata&#8221;&lt;/p&gt;&lt;/blockquote&gt;

or this:


Then the Un-Encode Entities plugin will convert it to this:

<blockquote><p>&#8220;Arte non è mai finita, è solo abbandonata&#8221;</p></blockquote>

You can download it here: Un-Encode Entities for Coda. (Requires Coda for Mac OSX).

How to integrate jQuery with Magento

jQuery and Magento

I recently ran in to this problem whist developing an e-commerce site using the Magento platform. I needed to incorporate Flowplayer in to the site and for that purpose I wanted to use jQuery. The problem is that Magento relies heavily on the Prototype library which uses the same ($) selectors as jQuery so simply including jQuery causes both libraries to stop working. Here’s how to go about it…

1 If you want to use jQuery on all pages, then you start by adding the jquery script to…


…add the following line below the other script entries:

<action method="addJs"><script type="text/javascript" src="PATH TO YOUR COPY OF JQUERY"></script></action>

2 However, if you only want to use jQuery on certain pages (for example on certain product pages), you need to go to the product page in the admin panel ‘catlog → manage products’ then select the appropriate product page. Now, select the ‘Design’ section and add the following xml in to the ‘Custom Layout Update’ box:

<reference name="head">
	<action method="addItem">

In this case the place to put your jQuery.js file is: ‘/skin/forntend/base/default/jQuery.js’.

3 Now, when using jQuery you must ensure it is using ‘noConflict’ mode. To do this, add:

var $j=jQuery.noConflict();

to the end of your jQuery script.

and now, alter any jQuery code as follows. If you have:

$("button").click(function () {

alter it to:

$j("button").click(function () {

You can include any jQuery scripts either globally (as in stage 1) or on a per page basis (as in stage 2).

And now you should have jQuery working on your Magento site.

You can find more information on the jQuery noConflict mode here: http://api.jquery.com/jQuery.noConflict/

See your website as a search engine sees it with Lynx

So you’ve created a great design, you’ve built the site and you’ve written and added the content. Everything’s looking good — or is it?

Sometimes it helps to step back from the design and see the site as a search engine will see and index it. This is where the Lynx browser can be very helpful. Basically Lynx is a cross-platform text-based browser that runs in the command line. Originally it was developed for UNIX but DOS versions are also available that run under all versions of Windows.

First of all you will need to install Lynx. The Lynx project is hosted at http://lynx.isc.org, however you can download a packaged version for Mac from Softpedia: http://mac.softpedia.com/progDownload/Lynx-Download-7825.html (at the time of writing the latest version is 2.8.7).

After installing the Lynx Browser, open Terminal.app and enter the command: lynx

The browser will then open in the terminal window. From here type: g (for go), then enter and you will be prompted for a URL. Simply enter the URL you wish to view.

Lynx 2.8.7

It’s always a good idea to check your page with all images/javascript etc. turned off. Read it through, is it as you expected? Does it get the message across that you want? Does the content appear in the order that you were expecting? If the answer to any of these questions is no, maybe you need to re-think your content and/or structure.

Ever wanted to know how many lines of code you have written?

Whilst working on a large site, or even a moderately sized one, there may come a time when you stop and think ‘Just how many lines have I coded?’. Today I’m going to show you a very simple way to find the answer, and also break it down into languages, HTML, PHP, Javascript, etc…

1 First of all you need to download a copy of the Perl script Cloc. You can get it from http://sourceforge.net/projects/cloc/files/ — the latest version is 1.53.

2 Download the script (if you have copied and pasted it from the browser window, make sure you give it the .pl Perl extension).

3 Next, open up Terminal.app and navigate to the script. I put mine in a folder called ‘TerminalScripts’ in my home folder, so…

cd TerminalScripts

…gets me there.

4 Run the cloc script, referencing the folder containing the project you want to analyse eg:

perl cloc-1.53.pl /Users/duncan/Webserver/OxfordTravelGuide-SVN

Cloc 1.53

And that’s it, simple!

10 Mac Apps for Web Design and Development

I thought it’d make an interesting experiment to post my current top 10 apps for Web Design and Development on the Mac now at the beginning of the year, and then follow up at the end of the year to see what, if anything, changes.

So without further ado, here are my top 10 apps (in no particular order) for web design and development on the Mac:

1 MAMP, MAMP pro

MAMP pro

It’s always best practice to develop and test everything locally before uploading to a server, and whilst the Mac comes with an Apache Server & MySQL already installed, I use MAMP. It’s quick to install and get up and running, and easilly configurable from it’s simple interface. An installation of MAMP gives you an Apache server with PHP and MySQL and the ability to locate the root level of your localhost server anywhere on your Mac. The basic MAMP installation is free but the paid for MAMP Pro is much more configurable and it allows you to setup multiple virtual hosts, and use Dynamic DNS.

version: 1.9.4
developer: appsolute GmbH
site: http://www.mamp.info/
Price: MAMP: free / MAMP Pro: €29.00

2 Subversion


Developing and maintaining a project would be a nightmare without some kind of version control. I use Subversion, as it plays well with my choice of editor (Coda — see number 4). Subversion can be a struggle to learn, but once learnt it definitely makes life easier.

version: 1.6.11
developer: CollabNet
site: http://www.open.collab.net/
Price: free

3 SequelPro


So now we’ve got the server environment and version control set up, what about working with MySQL?. I could use the command line or PHPMyAdmin which comes preinstalled in the MAMP package, however, on the Mac you can’t go wrong with SequelPro. It’s simple, powerful and free, giving you direct access to all your databases both local and remote.

developer: mjmedia
site: http://www.sequelpro.com/
Price: free

4 Coda


Finally on to the coding! I’m currently using Coda from Panic. It’s not quite a full IDE, but it does a lot and makes what it does do very easy. To begin with, it’s a text editor based on the popular SubEthaEdit text engine, it features syntax modes for ActionScript, ASP-HTML, CFML, CSS, ERB, HTML, Java, Javascript, JSP-HTML, LassoScript-HTML, Objective-J, Perl, PHP-HTML, Python, Ruby, Smarty, SQL & XML and additional syntax modes can be added. Whilst coding HTML it can validate on the fly. It gives coding hints as you type (great if you can’t quite remember the syntax for that php function!). It supports Subversion for version control and it is extensible both with AppleScript and third-party plugins. Coda has built-in FTP (it uses the same FTP engine as Panic’s top Transmit app). As well as all this Coda has a built-in GUI for coding CSS, a preview mode which allows you to browse the DOM, a built-in Terminal for when you need access to the command line and ‘books’ — a reference section giving you the complete run-down on HTML, CSS, Javascript and PHP.

version: 1.7
developer: Panic Inc.
site: http://www.panic.com/coda/
Price: $99.00

5 CSSEdit


Although Coda has a built-in GUI for handling CSS I still find myself coding all my CSS in CSSEdit from Macrabbit which I have been using for much longer than Coda. In fact, CSSEdit is the app that taught me CSS. The main window is split in to 3 columns, the left column contains all your classes, ids, selectors etc., the right column is a GUI for building your styles and the central column is a text editor for any manual adjustment you would like to make. On top of this, the Preview window gives you a live preview of your site which changes in real time as you edit your CSS. And that only scratches the surface of what this little app is capable of. If your developing on the Mac and you don’t have CSSEdit get it now!

version: 2.6.1
developer: Macrabbit
site: http://macrabbit.com/cssedit/
Price: €29.95

6 Kaleidoscope


When you have been working with version control for some time there will come a point when you want to either compare or merge a document with a previously archived version. If you have the Apple Developer Tools installed (they’re on your Mac OS X install CD) you can use FileMerge. However, a far more elegant solution is Kaleidoscope. As well a having a fantastic interface, Kaleidoscope has the ability to compare image files. Kaliedoscope can also be configured to work as the default diff app for Versions, TextMate, Cornerstone, Subversion (command line), Git, Mercurial, Bazzar and with a bit of command line persuasion Coda.

version: 1.1.1
developer: Sofa
site: http://www.kaleidoscopeapp.com/
Price: €29.00

7 Pixelmator


Anyone who is familiar with Photoshop will instantly have some idea of where Pixelmator is coming from. That’s not to say that it is a direct copy and whilst not as poweful as PS, it has some features and functionalitiy that is in fact better. Pixelmator can only handle RGB but as I’m using it for web graphics that’s just fine. Pixelmator uses Apple’s in-built quartz filters for image effects, so if you have Apple’s Developer Tools installed and you know your way around Quartz Composer, you should be able to build your own. All the familiar features are here, selection tools, gradients, brushes (it even supports Photoshop brushes). It can open and save in the .PSD format although some features like layer effects are not supported. It’s not a complete replacement for Photoshop (one thing I miss is some kind of path tool), but it can do most things – and for the price (E29 from the app store – which includes a free upgrade when version 2.0 comes out) it’s just great!

version: 1.6.2
developer: Pixelmator Team
site: http://www.pixelmator.com/
Price: €29.00 (Mac app store special offer)

8 Sketch


When it comes to designing icons I generally prefer to use a vector app. There are several alternative vector apps out there for Mac and each has it’s pros and cons. I am currently using Sketch which I got at a reduced price when I purchased the excellent Fontcase (see number 10). If you’re used to using Adobe Illustrator then this app can take a bit of getting used to, however, once learnt it’s really quite fun to use and for icon design it’s prefectly adequate. It creates files in it’s own .sketch format but it can export to .pdf, .eps. .svg, .jpg, .png and .tiff.

version: 1.0.6
developer: Bohemian Coding
site: http://bohemiancoding.com/sketch/
Price: €32.00

9 ImageOptim


This small utitliy is great! Before uploading any images I always run them through ImageOptim — if fact I have an Automator action set up to process them and the upload to my server. Basically ImageOptim is a GUI for several command line utilities (PNGOUT, PNGCrush, OptiPNG, AdvPNG, JPEGOptim, Jpegtran & Gifsicle). Even after saving an image using Photoshop’s Save for Web feature you can make considerable savings on the size of images (PNGs in particular) by running them through ImageOptim.

version: 1.2.5
developer: Kornel Lesiński
site: http://imageoptim.pornel.net/
Price: free

10 Fontcase


When it comes to Font Management the Mac’s built-in Font Book is not really up to the job — enter Fontcase. Fontcase is a kind of ‘iTunes for fonts’, it makes organizing, activating, and choosing fonts easy and enjoyable.

version: 1.5.8
developer: Bohemian Coding
site: http://bohemiancoding.com/fontcase/
Price: €42.00


Whilst I’m not claiming these apps are the best out there — although one or two (Fontcase and CSSEdit spring to mind) probably are — I am using them all on a more or less daily basis. It will be interesting to see how that changes over the course of 2011.

@font-face embedding made simple with Font Squirrel

font squirrel

Font Squirrel makes font embedding with CSS a cross-browser reality!

The CSS @font-face rule is hardly new — in fact it was proposed in CSS2 and has even been supported in Internet Explorer since version 4! The problem has always been that different browsers have implemented it in diverse ways. IE, for example has implemented it using the Embedded Open Type format (.eot), whereas Safari, which has supported @font-face since version 3.1 has opted to use TrueType (.ttf) and OpenType (.oft). Now with Firefox (v3.1) and Chrome also supporting @font-face, using it has become an option.

Recently, in my article “Use the Google Font API to break away from web safe fonts” (Nov 20th 2010), I showed you how to use the Google Font API to replace the standard set of web-safe fonts easily. The main limitation of the Google Font API is its limited library (currently only 34 fonts — not many, but still a vast improvement on the standard web-safe set). However, Font Squirrel has (at the time of writing) a total of 634 font families that are all licensed as free for commercial use! many of these fonts can be downloaded directly from the site, but some require you to follow a link to the designer’s or foundry’s site.

There are also hundreds of ready-prepared font kits to download. Each kit contains the following:

  • TrueType fonts (Firefox 3.5+ , Opera 10+, Safari 3.1+, Chrome
  • EOT fonts (Internet Explorer 4+)
  • WOFF fonts (Firefox 3.6+, Internet Explorer 9+, Chrome 5+)
  • SVG fonts (iPad and iPhone)
  • Cufón fonts (in case you want them)
  • Demo.html and stylesheet.css examples

You can also make generate your own kits by using Font Squirrel’s @font-face Generator. Here’s an example of how, using Sansation by Bernd Montag (available from the Font Squirrel site):

font generator

1 First, go to the Generator (http://www.fontsquirrel.com/fontface/generator) and click the ‘+Add Fonts’ button to add the Font from your system — navigate until you locate the font and click OK. You can process several fonts at once, but as the state, the generator is processor intensive, so be kind and don’t generate more than a few at a time.

2 Click the Agreement check box (remember, you can only use fonts that are licensed for use online), then simply click the ‘Download Your Kit’ button.

3 You should now have downloaded the font kit which contains the following files:

generated web fonts

  • generator_config.txt
  • sansation_demo.html
  • sansation_regular-webfont.eot
  • sansation_regular-webfont.svg
  • sansation_regular-webfont.ttf
  • sansation_regular-webfont.woff
  • specimen_files
  • stylesheet.css

generator_config.txt contains any customized settings you may have used when generating your fonts, and can be uploaded to the generator to set it up for processing fonts using the same settings.

sansation_demo.html contains a demonstration page using the webfonts at all difference sizes, a sample layout using the fonts, a complete listing of available characters in the webfonts & full instructions for their use.

The 4 files, .eot, .svg, .ttf & .woff are, of course, the generated web fonts.

specimen_files just contains some CSS and Javascript that is used for presentation on the demo.

stylesheet.css contains the necessary CSS for use on your site.

4 Rename the folder (eg: webfonts) then upload the folder to your server and link to the CSS in your html:

<link rel="stylesheet" href="webfonts/stylesheet.css" type="text/css" charset="utf-8" />

Font Sample

5 Now to use the font (for example as an <h1> title), simply specify it in your CSS (remembering to provide an alternative stack for unsupported browsers):

h1 {
	font: 28px SansationRegular, Verdana, Arial, Helvetica, sans-serif;
	color: #61b2f3;
	padding-bottom: 10px;

You can see the downloaded demo page for this font here.

Convert to entities – a widget for Mac OS X


Well, I did promise in my last post that I would be creating some more useful widgets for web development — and here is one of them:

ConvertToEntities can convert any text / code / etc. to entitles for use in html or Javascript. Whether you want to obfuscate an email address using javascript, or you simply want to know the character code for, say ‘π’ you can do it with this widget.

xkcd widget

And finally, I couldn’t help it — whilst I was working on ConvertToEntities, I also hammered out a feed widget for the xkcd webcomic to save myself from having to visit the site every Monday, Wednesday & Friday.

You can download them both from my downloads page. Enjoy!

How to paginate a random list using PHP and MySQL

Displaying a list of data from your MySQL database and the breaking the result up in to pages is fairly straightforward to achieve, you simply need to two variables in PHP. One for the amount of data you wish to display on each page $amount=20; and another to control the pagination $offset=0. The MySQL query is a follows:

$query="SELECT * FROM my_table LIMIT $amount OFFSET $offset";

You can then set up your NEXT / PREVIOUS links and pass the $offset value in the URL. If you have set $amount to 20, then $offset=0 will display page 1, $offset=20 page 2 & $offset=40 page 3 etc…

Very easy — you can adjust your query to display data in any order you like, alphabetical, reversed by date etc. — but what if you want to display the data in a random order?

$query="SELECT * FROM my_table ORDER BY RAND() LIMIT $amount OFFSET $offset";

You can see the problem instantly — the first page will display $amount of data in a random order, OK, but the second page will display $amount of data in a new random order — it may contain items that were displayed on the first page!

So how can you move between pages simply, but retain your random list? The solution is to ‘seed’ a random number. It works like this:


$query="SELECT * FROM my_table ORDER BY RAND($seed) LIMIT $amount OFFSET $offset";

Once RAND() is seeded MySQL will produce a randomized list that is repeatable. I this way it is possible to repeat the query using LIMIT & OFFSET to produce pagination. In the above example $seed is a fixed number, but it would be better to set $seed to a random number and store it as a $_SESSION variable.

Here’s an example of a page that has pagination and data presented in a random order. In this example, instead of storing the $seed in a $_SESSION variable, the seed is generated using a combination of the visitor’s IP address and the current date and hour…

//generate individual seed...

…in this way, everyone sees a different random list that is reordered every hour.

How to use Subversion version control with Coda on the Mac

For those of you who don’t know, Subversion is a version control system. Basically it enables you to track all changes to a project. It gives added security and control to the integrity of your work enabling you to compare a document with any previously saved version, and revert to, or merge different versions of a document.

Coda for MacIn this tutorial I will show you how to set up Subversion to work with Coda on the Mac. Coda from Panic Inc. is my app of choice when it come comes to web development on the Mac — it may not do everything, but it does a lot and it makes working with Subversion a cinch!

For the purposes of this tutorial I will assume that you develop sites locally, as I do, using MAMP and will be installing Subversion locally to manage your projects as you work on them.

1 First you need to get yourself a copy of Subversion. Go to http://www.open.collab.net/downloads/community/ and download the latest binaries, then install. (the installer will install Subversion to: /opt/subversion/bin/svn ).

terminal.app2 The next thing you need to do is create a repository. The repository is where all of your versioned data will be stored. You can locate it anywhere you like, personally I have mine in my home directory, where I also have the directory that is the root level of my localhost server. To create the repository, you need to access the command line. Open a terminal window and navigate to your chosen location (in my case: cd /Users/duncan/) and then create the repository: svnadmin create SVNrep – this will create a repository in the home folder called SVNrep.

3 OK, now that SVN is installed and you’ve created a repo, you need to configure it. In the Finder, open the directory ‘conf’ that resides inside your repo. (in this case /Users/duncan/SVNrep/conf/). Using a text editor, open the files svnserve.conf and passed. In svnserve, you need to uncomment and amend the following lines:

anon-access = none
auth-access = read
password-db = passwd
realm = My Repo

Save and close this file, then add a line to the passwd file to set your username and password, for example:

myusername = mypassword

Then save and close the passwd file.

4 Now to add your project to the repo – again, this will be done using the command line. Again, I’m assuming that you have many sites on the go, and each is sitting in a separate folder on your server – let’s say you have one called ‘my_great_site’. To add this to the repo type the following:

svn import my_great_site file:///Users/duncan/SVNrep/my_great_site -m “Initial import”

The path will be different for you depending on where you have put your repo and what you have called it.

5 Now you can delete you site as its safely stored in the repo (OK, you don’t want to delete it, just move it out of the root level of your server and archive it somewhere).

6 To work on your site, you need to checkout a ‘working copy’ from your repository (terminal again!). Type the following:

svn checkout file:///Users/duncan/SVNrep/my_great_site Webserver/my_great_site-SVN

As before you may need to adjust the paths depending on A. where you repository is (in this case: /Users/duncan/SVNrep, and where your server root is: /Users/duncan/Webserver/ ). The final -SVN is not necessary, it’s just my way of visually marking the project as being under version control.

Coda preferences

7 OK, now the project has been checked out, it’s time to update your site settings in Coda. First, open the preferences – Coda > Preferences… and click on the ‘Files’ tab. Enter /opt/subversion/bin/svn into the ‘Subversion Tool Path:’ field, then close the preferences.

8 Nearly done, now it’s time to update your site settings in Coda. Open the ‘Sites’ tab and click on the ‘i’ icon for your site. (pic). If you added -SVN to your checked out copy (or called it something different entirely, you will need to adjust the ‘Local URL:’ and ‘Local Root:’ fields). Now scroll down to the bottom, and expand the ‘Source Control’ section. Check the ‘Enabled’ checkbox and then enter you username and password that you set up in stage 3. If the Repository URL is not already set, close the sites panel and open it again. If it’s still not set you may need to add it manually – in this case it would be: file:///Users/duncan/SVNrep/my_great_site

Coda sites panel

9 That’s it – your site is now under source control, check out the ‘Managing Files With Source Control’ section of the Coda Help files – enjoy!

How to create Friendly URLs

What are Friendly URLs? Friendly URLs (sometimes know as tidy urls) are dynamic URLs (URLs with a query string attached) URLs that have been ‘re-written’ to appear as static pages — usually retaining important keywords and information in them. An example would be a product page that contained a list of product information retrieved from a database, with a search facility to enable you to see a product category in more detail. For example, the main page showing all products might be:


and when showing a product category, it might be:


A re-written Friendly URL for the above might look something like this:


So, how is it done? Well, there is more than one method to achieve Friendly URLs but the method I tend to use involves using .htaccess files. (note: this method will only work if you are using an Apache server with mod_rewrite enabled).

Create a text file (name it anything you like), open it and add the following lines:

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^products-([^/\.]+)_([^/\.]+).html?$ products.php?category=$1&colour=$2 [L]


Once you have created the text file, upload it to the root level of your site and then change its name to “.htaccess”. (Note: htaccess files are invisible files, check first if there is one there already and if so, open it and copy & paste the text in to it).

The last thing you need to do is update any references to the URL in you html to use the new URL.

It’s pretty easy to pick up the basics, however – to make it even easier I have created a simple web app for creating .htaccess based Friendly URLs. Simply enter your exsisting full URL with query string, then make the appropriate choices to create your new URL and finally download your .htaccess file, ready to upload to your server.

Dynamic CSS – how to use PHP in your stylesheets

Q: Can you use PHP in your stylesheets?

A: yes, of course!

But why would you want to? Well, maybe you want your users to be able to control the font size or colour scheme on your site. Or maybe you need so supply and style individual IDs to dynamically generated content. Or maybe you want to change the header image depending on the time of day (like I do on this site). Whatever your reason it’s very simple to achieve.

Perhaps the most simple method would be to include the styles in question in the <head> section of your HTML and manipulate them there, something like…

<style type="text/css">

## add you PHP here...


…however, that’s a bit untidy — if you want to move ALL your CSS, static & dynamic into one stylesheet, here’s how…

1 Rename your style sheet to give it a .php extension eg: style.css → styles.php

2 This on its own will not work, you need to inform PHP that it is dealing with CSS, this is done by adding a PHP header to your stylesheet. Add the following to the top of your stylesheet.

header("Content-type: text/css");

From now on you can add any PHP you require to your CSS file.

3 One more thing. You need to change the reference to your css file to make sure it is linking to the PHP file, something like:

<link rel="stylesheet" type="text/css" media="screen" href="css/styles.php" />

4 Or, if you prefer, and your site is hosted on an Apache server, you could use mod_rewrite to rewrite the url to do this, you would need to create a file called .htaccess* in the root level of your site containing the following code (if it already exsists, copy and paste the code into it):

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^css/styles.css /css/styles.php [L]

this tells all calls to styles.css to access styles.php

* more on mod_rewrite & .htaccess files coming soon…

Tracking outbound links that open a new window with Google Analytics

So, here’s the problem:

…you want to use the tracking feature of Google Analytics to track all clicks on outbound links from your site, however, you also want those outbound links to open a new window…

If you simply follow the instructions to track outbound links you will discover that your links will no longer open in a new window (regardless of whether you are using Javascript or target=”_BLANK” to open the window.

And here’s the solution:

Apply the javascript to you hyperlink as usual…

<a href="http://www.example.com" onclick="recordOutboundLink(this, 'Outbound Links', 'example.com');return false;">your link text</a>

…but modify the tracking code as follows…

function recordOutboundLink(link, category, action) {
  try {
    var pageTracker=_gat._getTracker("XX-XXXXXXX-XX");
    pageTracker._trackEvent(category, action);
    setTimeout('document.location = "' + link.href + '"', 100;window.open(this.href))

(Don’t forget to replace XX-XXXXXXX-XX with your tracking code)

…and that’s all — Outbound links with Google Analytics tracking and opening in a new window.