Removing widows

After reading an article from CSS Tricks: Preventing Widows in Post Titles I decided it was about time to make my first jQuery plugin, the Widow Remover.

The Problem: A single word alone on it’s own line.

The Solution: add in a non-breaking space


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(function($) {
	$.fn.widow_remover = function(params) {
		params = $.extend( {words: 1}, params);
 
		this.each(function() {
			var string = $(this).text();
			var sp = string.lastIndexOf(' ');
			if(sp != -1){
				do{
					string = string.slice(0,sp)+' '+string.slice(sp+1);
					params.words -=1;
					sp = string.lastIndexOf(' ');
				}while(params.words>0 && sp != -1);
			}
			$(this).html(string);
		});
		return this;
	};
})(jQuery);

Usage:

1
jQuery('h1').widow_remover();

Result:

No more single words on a line

Still needs some improvements as looking back on it parts of the code I think I was in daze but the basic idea is there and hopefully it helps someone out

The Code is hosted at code.google.com and at plugins.jquery.com

You can leave a response, or trackback from your own site.

Leave a Reply

Free Sprint phones for sale | Thanks to CD Rates, Reverse Phone and Registry Software