Studio moh


How Dylan avoids widows

Typographical widows, that is. Learning jQuery (an excellent blog, even for the power users) had a wonderful post on how to use jQuery to append widows.

(If you didn’t take a print class in high school, a widow is a word that ends on the next line like
this.

This is a print master’s nightmare and a typographical no-no.)

Their solution uses regular expressions, which is nice, but not the most efficient way to split strings, and a bit of a memory hog on older systems.

Why not use CSS property white-space: nowrap;?

$('h2').each(function() {
var h2Contents = $(this).html().split(" ");
h2Contents[h2Contents.length-2] = '<span style="white-space: nowrap; color: red;">' + h2Contents[h2Contents.length-2];
h2Contents[h2Contents.length-1] = h2Contents[h2Contents.length-1] + '</span>';
$(this).html(h2Contents.join(' '));
});

This snippit of jQuery wraps the last two words of every H2 tag with a span tag that has an inline style that prevents line-breaks. The result? No more widows without the performance hit of Regex.

Post a Comment

Your email is never shared. Required fields are marked *

*
*