more jQuery typography

Share/Save

You should check out "Use the Best Available Ampersand" from SimpleBits. I love me some ampersands, and that post is a great resource for prettifying your site's ampersands with a little CSS typography.

Along the lines of last week's jQuery "widon't" post, you can offload some of the typography processing to the browser. It's really slick and simple if you have jQuery enabled.

To use some of his ampersandy style goodness, add this JavaScript snippet to your site somewhere:

jQuery(function($){
 
$('h1,h2,h3,h4,h5,h6').each(
    function(){
        $(this).html($(this).html().replace(/&amp;/g,'<span class="amp">&amp;<\/span>'));
    }
);
 
});

Then simply add a few CSS font style rules to your site's stylesheets for span.amp, and you're set.

If you want to be really rad, you could combine this with widon't, like so:

jQuery(function($){
 
$('h1,h2,h3,h4,h5,h6').each(
    function(){
        $(this).html($(this).html().replace(/&amp;/g,'<span class="amp">&amp;<\/span>').replace(/\s([^\s>]{0,10})\s*$/,'&nbsp;$1'));
    }
);
 
});

Now your website is 2x hotter, guaranteed :)

Updated, per Paul's comment, to use jQuery's $.html instead of manipulating innerHTML on the actual DOM elements. Also updated to use a DOM ready callback, making it easier on folks who just want to copy/paste these snippets into their site.

Comments

Especially if you use any ampersands?

Most especially.

Hmm, this looks really nice but I can't get it to work at all. Do you have any demos?

No worries, I think I have it.

That was quick :)

Hi

I'm starting a collection of typography enhancements that can be applied to pages via jQuery. This (and the widon't one) are awesome.

One note:

innerHTML isn't really leveraging jQuery, for example:

this.innerHTML = this.innerHTML.replace(/&amp;/g,'<span class="amp">&amp;<\/span>');

could be (maybe should be):

$(this).html( $(this).html().replace(/&amp;/g,'<span class="amp">&amp;<\/span>') );

... works just as well and is 'guaranteed' compatability across browsers & future versions of jQuery.

It's also useful to use something like this:

$(this).text( $(this).text().replace(/&amp;/g,'<span class="amp">&amp;<\/span>') );

You're right, I should have known better. Thanks for pointing that out :)

The $.text example you gave is bound to cause some problems, though. You're going to end up with a bunch of escaped span tags wrapping all your ampersands.

The examples in my post (and the widon't post) have all been updated to use $.html instead of innerHTML. I also added DOM ready callbacks.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

More information about formatting options