WP-Mix

A fresh mix of code snippets and tutorials

jQuery prevent widows

While redesigning DigWP.com, I was experimenting with different layouts for the comments section. In one of those layouts, I needed to prevent widows in the comment text (when it comes to cleanly displayed text, widows are the worst). So after some playing, I came up with a couple of jQuery snippets that work great. Here they are for future reference.

Prevent widows (first child paragraph)

For the comments layout that I was fiddling with, the user’s avatar was floated left, such that the text contained in the first comment paragraph wrapped when it contained a sufficient amount of text. In CSS, the selector looked like this:

.comment-text p:first-child {}

The problem was that, for quite a few comments, the first paragraph had just enough text to wrap, but only with a word or two. So there were all of these weird looking widows scattered throughout the thread of comments.

So maybe jQuery to the rescue. To eliminate the widows in the first (child) paragraph, I tried this code snippet, which works well:

$('.comment-text').each(function(){
	$('p:first-child', this).each(function(){
		var string = $.trim($(this).html());
		string = string.replace(/ ([^ ]*) ([^ ]*)$/,' $1 $2');
		$(this).html(string);
	});
});

That script basically targets the first paragraph of each comment-text <div>, and then replaces the last two regular spaces with non-breaking spaces. The non-breaking spaces ensure that the last wrapping bit of text include at least three words.

Prevent widows (all paragraphs)

So the previous technique worked well, but there were still a bunch of widows in other paragraphs. So with a few modifications, I tried this snippet to prevent widows in all paragraphs:

$('.comment-text').each(function(){
	var string = $.trim($(this).html());
	string = string.replace(/ ([^ ]*) ([^ ]*)$/,'&nbsp;$1&nbsp;$2');
	$(this).html(string);
});

This does the same thing as the previous script, only instead of preventing widows for the first paragraph, it prevents them in all paragraphs.

In the end, I decided against the floated avatars in the comments section, and just went with two columns to prevent widows in the first paragraph. And to eliminate widows in other paragraphs, I simply changed the width of the .comment-text <div>. To see the finished product, check out the comments section on the redesign announcement post.

★ Pro Tip:

SES Pro