jQuery first-letter hijinks
Aug15th
2009
••
This morning I was flipping through Memphis Magazine and noticed a pretty simple yet nice text treatment. They were over laying the first paragraph over a faint colored square that had the first letter of said paragraph in it. Nice way of adding a little ‘pop’ to the page.
Of course I thought to myself how to do that. So borrowing some script from Learning jQuery I whipped up this little demo.
The JavaScript is pretty straight forward, most of it remains unchanged from the aforementioned tutorial from Learning jQuery.
/* global functions */
function bg_letter() {
var first_paragraph = $('#content p')[0];
if (!first_paragraph) return false;
var node = first_paragraph;
while (node.childNodes.length) {
node = node.firstChild;
}
var text = node.nodeValue;
var first_letter = text.substr(0,1);
var match = /[a-zA-Z]/.test(first_letter);
if ( match ) {
var letter = 'transparent url(alphabet/' + first_letter.toLowerCase() + '.gif) top left no-repeat';
$(first_paragraph).css({'background' : letter, 'font' : '16px/22px "futura bk", century gothic, verdana, sans-serif', 'padding' : '16px 0 0 16px', 'margin' : '0 0 0 -16px'});
}
}
/* begin jquery */
$(document).ready(function(){
bg_letter();
});
The difference is what it does on ‘match’. I went ahead and made a variable, less for legibility than just to see how it was done.
if ( match ) {
var letter = 'transparent url(alphabet/' + first_letter.toLowerCase() + '.gif) top left no-repeat';
$(first_paragraph).css({'background' : letter, 'font' : '16px/22px "futura bk", century gothic, verdana, sans-serif', 'padding' : '16px 0 0 16px', 'margin' : '0 0 0 -16px'});
}
The variable ‘letter’ has the local path to the alphabet folder where all the images for each letter or stored. The first_letter_toLowerCase() adds that letter to the image file. So you need 26 images in that folder for English.
Then I just applied a little inline CSS to the first paragraph defining the background image, font size, weight and line height. I then padded the text to sit nicely on top of the letter and a little negative margins to pull the paragraph in to line with the rest of the text. Plus that gives it a little more flare IMO.
Nothing too super fabulous but, nifty none the less. And heck, It’s middle of August and I had an hour to kill. Enjoy.












