— tomauger.com

Randomizing lettering baseline with vertical-align, jQuery and lettering.js

Check this code snippet out. Include jQuery and the most excellent lettering.js jQuery plugin by Dave Rupert and the guys at Paravel, inc, and then paste this into a script tag, or whatever you do to get JavaScript on your page. Then, just customize the list of classes that will be “bumped”.

// Bump.js by Tom Auger (http://www.tomauger.com). Free to use for anything. Maybe leave this line intact?
 
// Set up some customization here for the randomness
var classes = [
	// ['css selector', vertical-align variance (in pixels) eg: 2 = -2px to +2px, % chance of getting 'bumped']
	['.text', 1, 10],
	['#hours', 1, 50],
	['.textlist li', 1, 20]
]
 
jQuery(document).ready(function($){
	// Everything's been loaded, let's have some fun!
	for (var i=0, l=classes.length; i Math.random()) $(this).css('vertical-align', Math.floor(Math.random()*(shift*2+1))-shift + "px");
		});
	}
});

Customizing Bump.js

It’s really easy to customize how this script affects your HTML elements. You need to customize the “classes” array in order to reflect the css classes and selectors that your HTML document is using. The three examples that are provided will affect:

  • all HTML elements that have a class of “text” assigned to them
  • any HTML element whose ID is “hours”
  • any LI element that’s inside any HTML element with a class of “textlist”

It’s just jQuery, so if you’re familiar with jQuery selectors, this should be a breeze.

The next parameter is the amount of “bump”. This should always be a positive integer (ie: 1, 4, 10 but NOT -4, 3.6 or .0002). The script will take this number as a range. So a value of “2″ actually translates into a random number between 2 and -2, inclusive. Do NOT add “px” to the end – the script takes care of that.

The final parameter is the % chance that each letter will be “bumped”. So 100 means 100%: every letter will be given some bump, based on the amount you specified in parameter 2. 10 means 10% – so 10% of all letters will get “bumped”.

Note that in this current algorithm, there’s a chance that, even if a letter is selected to be “bumped” it may be bumped by 0 px, so it will look like it wasn’t “bumped”. So even with a setting of 100% some letters will align to their original baseline.

How it works

The real heavy lifting, of course, is done with lettering.js. When you run the lettering() method on a jQuery element, lettering.js wraps each individual text character inside that element with its own <span> tag. So then my script comes along, and iterates through each of those <span>s and assigns a random vertical-align value to it (in an inline style attribute).

Cheap and cheerful!

I should turn this into a plugin, but that seems like more trouble than it’s worth. Let’s say if this post hits 5,000 reads or 20 comments asking me to do it, I’ll do it. For the children.