Typographical grid plugin

Here’s a snippet I wrote the other day that overlays the page with a typographical/layout grid when activated. Others exist, but very few, and not with the functionality I wanted, so there’s room for another.

I made it into a jQuery plugin simply to make it clear it’s dependent on jQuery: It’s not suitable for chaining (which apparently makes it a “utility plugin“).

Also, I’ve namespaced it as the rather vague ‘devTools’ in order to allow me to possibly add more tools to the plugin later while maintaining backwards compatibility. Hope you find a use for it!

Demo

Usage

Activation

$.devTools.grid(
	[columns], [column width (px)], [column margins (px)], {[optional configuration]}
);

Optional configuration

Key Notes Example Default
qs Value of query string value to look for if grid is to be activated that way. false leads the grid to be shown on load. ‘grid=true’ false
id The id used for the div containing the columns. ‘myGridContainer’ ‘browserToolsGrid’
container the element the grid is to be appended to. ‘#myContent’ ‘body’
center A boolean stating whether your website is centered. true false
color the colour of the grid. rgba is best so you can see through the grid. ‘rgba(200, 200, 100, 0.3)’ ‘rgba(204, 243, 204, 0.3)’
textColor the colour of the info text. ‘#ccc’ ‘#aaa’
outerMargins Use far left and far right margins true false
toggle Show the toggle button. false true

Example

Centered site, activated by adding ‘grid’ to the query string

$(function () {
	$.devTools.grid(16, 45, 15, {
		center:true,
		qs:'grid'
	});
});

More complex example

A double grid (with sub columns), shown by default.

$.devTools.grid(6, 158, 2 , {
	hideToggle: true
});
$.devTools.grid(6, 98, 62 , {
	hideText: true
});

Download

devTools.grid()

Battleships GS

In the spirit of a brand new month of April, I’d like to launch my latest personal project. It’s an open-source, online, multi-player, real-time, cloud-based, gaming platform, with the age-old classic ‘Battleships’ as the first release. You’d be a fool not to try it out:

Play Battleships GS now!.

How to play

  • Take a copy of the game (File > Make a copy…)
  • Share your copy with a friend (share button, top right)
  • Follow the instructions on the opening tab of the spreadsheet.

Asynchronously reloading the Twitter JS widget

As anyone who’s used it knows, the standard JS Twitter Widget document.write-s itself into the page by default. This obviously sucks because a) you have to have the JS for it mixed up in your content, which in turn means b) if it hangs for some reason, all content after the widget is held up.

Asynchronous loading

The way round that (as others have found out before me) is to use an undocumented API argunment “id”, which defines the ID you would like the Widget written into. This in turn allows you to call the widget code as a function on, for example, JQuery’s document.ready, shown below, which in turn allows you to load Twitter’s widget.js at the bottom of the page, even using $.getScript() to delay it even further:

// Note: This function should not be global like this in real world use
function renderTwitterWidget(){
	new TWTR.Widget({
		id: 'iTwitterContainer', 

		// ...Rest of normal Twitter widget code... 

	}).render().start();
} 

$(function () {
	$.getScript('http://widgets.twimg.com/j/2/widget.js', function(){
		renderTwitterWidget ();
	});
});

There: Fail Whale proof.

Asynchronous reloading

Thing is the design required that the user be able to refresh the widget with a different search term. The above code can do that, with a couple of additions:

  1. Add the search term as a parameter to be sent to the function.
  2. Use the .stop() method (found by searching the Twitter Widget source) to kill off previous instances’ setTimeouts, which otherwise carries on populating your container with the previously chosen search term(s).
// Note: Again, this variable and function should not be global in real world use:
var twitterWidget = false;
function renderTwitterWidget(searchString){
	if (twitterWidget){
		twitterWidget.stop();
	}
	twitterWidget = new TWTR.Widget({
		id: 'iTwitterContainer',
		search: searchString, 

		// ...Rest of normal Twitter widget code...

	}).render().start();
} 

$(function () {
	$.getScript('http://widgets.twimg.com/j/2/widget.js', function(){
		$('.iTwitterLink').click(function(){
			renderTwitterWidget("New Search Term");
		});
	});
});

Separate CSS classes for Javascript

There was a mini debate among friends on Twitter recently about using separate class names for JavaScript. For example <div class="tab iTab">; with your CSS attached to “.tab” and your JS attached to “.iTab”.

Coincidentally this is something I started doing a few projects ago, thinking separation good / overloading bad, and I have to say I’m completely sold on it, here’s a few specific positive effects I’ve experienced:

Design / Markup changes shouldn’t break JS

If you want to style a list you might put a class on the ul, if you want those items to be interactive you might target links within the list like so: $(".listClass a")… Then the design or content changes and it no longer makes sense to have a list, you change it, and the JS falls apart.

CSS classes might not be best put on the interactive element

Imagine in the situation above you want the items on the list to be individually addressable by JS – so you need classes on each item. Do you then use those classes to style the list – even though each item might look the same? No – you put a class on the ul like before. In other words since the two types of class have different purposes, they should be treated – and named – separately.

It makes collaboration easier

A new front-end dev comes along, sees a CSS class with no styles applied, removes it for the sake of tidiness, JS stops working. Or, a new JS dev comes along, wants to update how the JS works, moves / renames the trigger class, layout falls apart. And for “new dev” you can also substitute yourself, updating the project 6 months later. :-)

Reusing code

You did a cool slideshow effect in that old project, and want to use it again, but with different styling – which are the class names you need to port over to the new markup to make it work? Cue hunt through the JS.

But…

One good counter argument I’ve seen is that this technique pollutes your HTML with traces of JavaScript, in the nasty way that onclick=”" used to.

This is fair on the surface, but if there are interactive elements there, using CSS classes to trigger, then that cross contamination has already happened. Much better in my book to be honest about it.

Colour grouping 8-bit CSS sprites

It’s reasonably well known that Fireworks can create alpha-transparent 8-bit png files (so can various other widgets but curiously, still not Firework’s celebrity sibling, Photoshop).

That’s an awesome trick, because they’re generally about a third of the size of 32-bit – however they are limited to 256 colours, which won’t work for CSS-spriting most designs.

Which leads me to a technique I’ve been trying recently: When you have a design with several clearly identifiable colour groups, make separate sprites for each colour – blue, red, purple, whatever – then export them as 8-bit.

Examples:

A recent Facebook game had a character sprite sheet that was a meg. I split out the character faces, that had lots of gradients and mixed colours into a 32-bit sprite (~200k) and 8-bit exported the mostly flat-fill, similar-coloured bodies (~200k), resulting in a hefty saving (~600k / 60%). (Note the heads and bodies were already separate as they were swoppable, so the split wasn’t a big deal.)

Another recent app had a design with several bold primary colours used for different icon and button sets. I went to town with this technique, making 4 colour-specific 8-bit sprites and a single 32-bit catch all sprite for the other colours and things that didn’t work at 8-bit:

Each sprite was at least 20k smaller than its 32-bit equivalent, which easily justifies the ‘weight’ of each extra file request (calculated by one BBC dev many years back as very roughly equivalent to ~2.5k on a default Apache install).

Corollaries:

This may not be a suitable technique for elements where there are

  • subtle or extensive gradients
  • a mix of of colours or
  • only a few items of that colour – where the saving won’t offset the downloading of an extra file

Looped playlist with SoundManager2

Just a quickie: The other day I had to add a backing track to a game. Stack Overflow lead me to the excellent SoundManager2 library, which features an extensive API and nifty HTML5 with Flash fallback behind the scenes to give maximum platform coverage & performance.

The only problem I had was finding an example of looping through a list of files endlessly, so I rolled my own, using simple recursion, and here it is in case it helps anyone else.

var audio = [];
// Array of files you'd like played
audio.playlist = [
	"/canvas/audio/Marissa_Car_Chase.mp3",
	"/canvas/audio/Vortex_Battl_Thru_Danger.mp3",
	"/canvas/audio/Gadgets_Activated.mp3",
	"/canvas/audio/Kids_Run_Into_Agents.mp3",
	"/canvas/audio/Jet_Luge_Chase.mp3"
];

function playAudio(playlistId){
	// Default playlistId to 0 if not supplied
	playlistId = playlistId ? playlistId : 0;
	// If SoundManager object exists, get rid of it...
	if (audio.nowPlaying){
		audio.nowPlaying.destruct();
		// ...and reset array key if end reached
		if(playlistId == audio.playlist.length){
			playlistId = 0;
		}
	}
	// Standard Sound Manager play sound function...
	soundManager.onready(function() {
		audio.nowPlaying = soundManager.createSound({
			id: 'sk4Audio',
			url: audio.playlist[playlistId],
			autoLoad: true,
			autoPlay: true,
			volume: 50,
			// ...with a recursive callback when play completes
			onfinish: function(){
				playlistId ++;
				playAudio(playlistId);
			}
		})
	});
}

// Start
playAudio[0];

(Note for clarity I’ve stripped out the surrounding code, including most scoping, so you’ll probably want to consider/remedy that if you use this.)

Remotely rebuilding a site

Ever had to redo a site design without access to the files? Sounds ridiculous I know, however that’s exactly what I had to do recently when applying the Starbucks rebrand and associated redesign to their non-US sites (e.g. Russia, Canada) and investor relations site.

The sites were hosted by Starbucks and build by a third party, and for security vs. tight schedule reasons they wanted to limit the update to overwriting assets, specifically CSS and images, so…

First step was to get a copy of their CSS onto my localhost (or whatever local http development space you have to hand). Straightforward enough.

Next I needed to persuade the browser, when viewing the live site, to redirect the request for that CSS to my copy.

Initially I did this by editing the path in the net inspector of Firebug, however I quickly realised this would be a pain if I accidentally refreshed. It also wouldn’t allow cross browser testing.

I then looked at Fiddler (a desktop proxy tool that allows you to inspect and interfere with browser requests) but couldn’t find the requisite functionality (please enlighten me if you know how). Then a colleague suggested Charles Web Debugger might do the job. Charles is similar to Fiddler, but I’d skipped it since it wasn’t free. Turns out it has a functionality complete trial however, and after a bit of a rummage I found it can bind specific request paths to new URLs. The benefit of that? It works for as long as Charles is running, and will apply to all browsers.
Now work could start, edit the local CSS, view the live site, see changes appear.

If the site is CSS-based (as in the investor relations site) all the design images will referenced from the CSS, so updating them just means hosting the new images locally alongside the CSS and updating the URL() values in the background{} declarations to reference the localhost. (Just remember to change them back before packaging up the files for delivery.)

If the site is a bit older (tables and img tags) you can locally host those images alongside the CSS and add new paths (including * wildcards if useful) to Charles. Bit of a pain, but then working with tables always was, right?

Browser support deprecation flowchart

From the archives of jobs gone by, I thought this little known doc might be of interest: The matrix of factors to be considered in deprecating browsers from the BBC’s browser support standard.

Alongside the BBC website visitor stats this chart (from the appendix of the BBC’s browser support standard) aims to provide a clear framework for discussion around dropping support for old (or picking up support for new) browsers.

As most web folk will know this is a source of constant bickering in the industry. Multiply this by the BBC’s public service remit and you have a recipe for some very long meetings, in one of which we were passed the suggestion of maintaining support for an old version of Safari because “mac users complain a lot”. Hmm.

I felt it was time we worked through the various factors that should be considered, and made a stab at their relative importance. This chart was the result.

While it doesn’t replace the discussions (there’s always be a special case or two to consider) anything that helps scope them and provide clarity is a win in my book.

Now – which of you Mac users wish to pick holes in it? ;-)

Simple JQuery rollovers with preload

Time for a snippet of code on this blog I reckon. The other day I wanted a simple JQuery rollover mechanism for some in-markup images, but after a bit of a hunt I gave up as the only preload machanisms I could find involved a whole plugin or knowing the names of all the images on the page) – so I rolled my own.

To use:

  1. add the class “rollover” to each anchor containing a rollover image
  2. name your rollover images the same as the original image, with the suffix “_on”, and place them in the same location as the original image
  3. finally, add the following to your onReady function:
// Preload
var rolloverImages = $('.rollover');
for(var i = 0; i &lt; rolloverImages.length; i++){
  var pic = new Image(1,1);
  pic.src = $('img', rolloverImages[i]).attr("src").split(".").join("_on.");
}
// Add hover functions
$(".rollover").hover(function() {
  $('img', this).attr("src", $('img', this).attr("src").split(".").join("_on."));
}, function() {
  $('img', this).attr("src", $('img', this).attr("src").split("_on.").join("."));
});

WordPress themes for webmonkeys

When I recently started looking for contracting web work for the first time in 10 years, I realised one useful skill to pick up would be writing WordPress themes: While I’ve not been looking it seems it has pretty much won the blog wars and along the way became a common CMS choice for small to medium sites, including my first contract site.

Looking round I found a bunch of starter tutorials for folks completely new to teh tubes, but not a lot for those who know their way around markup, servers and databases. On reflection that’s probably because it’s so easy, but what the hey – I’ve started typing now, so here’s my attempt:

1) Set up WordPress

I have a Dreamhost account, with installation of WordPress a siple option in their control panel, but even if you don’t have something similar from your hosting it’s (apparently famously) a 5 minute job: Unzip files to desired web location, create database, link database, run install/setup script.

To run on my desktop I turned to the trusty arms of Xampp, but any up to date PHP/MySQL setup will do.

2) Rummage in the reference theme files

Themes are php and client-side files added to wp-content/themes/  - There is no db entry/admin process required to add them.

By default in WordPress 3 the TwentyTen theme will be enabled. This is the reference theme, so is a good one for developers to poke around to understand how themes work, as each file has extensive commenting and links to the ‘Codex’ WordPress documentation, so you can very quickly start to learn your way round the php files.

3) Install/copy a theme to edit

Most WordPress themes will contain a whole bunch of functional server side stuff that you’re probably not going to change on any given project, so ideally you’d start with a CSS-less theme that just produces solid markup. I had a go at making one of these, but made the mistake of starting with an theme designed for WordPress 2. It’s a mistake I may yet rectify, but in the meantime you could do worse than using this HTML 5 one as a base.

Unzip the files into a new folder in the themes folder (named whatever you like), then edit the specially formatted metadata at the top of styles.css in the theme root (which by the way is a required WordPress file, so don’t move it). This comment block is used by the admin system to describe the theme.

3b) Parent themes

The quickest and cleanest way to create a theme with the same functionality as an existing theme, but different styling, is to use the existing theme as a parent (as I did with Kernel and JaneSexyLegs). Once you specify the ‘template’ attribute in the comment block at the top of styles.css then that ‘parent’ theme will be used as a base, which can be selectively overwritten and added to by adding files to the child. Take a look at the kernel and JaneSexyLegs zip to see a simple example.

4) Import some test content

There’s quite an array of features posts can have, so you want to be sure your theme covers all bases. This set of test data takes a pleasingly unit-test centred approach to its data. Import that (admin > tools > import) and you get a bunch of articles, each trying out a feature, including missing values, many tags, long titles and so on.

The import will involve your first light brush with WordPress plugins, which can do almost anything to your WordPress install – pushing it towards being a more powerful CMS, an ecommerce platform and so on.

5) Dive in!