Preventing Widows with Vanilla Javascript

What is a Widow?

When referring to text on a website, a “widow” refers to the final word of a heading or paragraph that wraps to its own line. Like this:

This is a line of
text.

To prevent this from happening, we can use the HTML entity for non-breaking spaces between the last two words:

This is a line of text.

A non-breaking space prevents the browser from adding a line break at that location, so it will drop the last two words to the following line like this:

This is a line
of text.

How to Prevent Widows with Javascript

Manually adding non-breaking spaces to all the text on our website is prohibitively time consuming, so here’s how we can do it with Javascript.

var nbspSelectors = [
	'h1',
	'h2',
	'h3',
	'h4',
	'h5',
	'h6',
	'p',
	'blockquote'
];

var nbspWordMin = 6;

nbspSelectors.forEach(function(selector) {
	var nbspElements = document.querySelectorAll(selector);
	nbspElements.forEach(function(element) {
		var wordCount = (element.innerHTML.split(" ").length);
		if (wordCount >= nbspWordMin ) {
			element.innerHTML = element.innerHTML.replace(/ ([^ ]*)$/,' $1');
		}
	});
});

First, we have the nbspSelectors array that defines all of the elements inside of which we want to prevent widows. In this example we have the most common text-focused HTML elements. However, we could also target elements based on ID or class name instead, like this:

var nbspSelectors = [
	'#no-widows',
	'.no-widows'
];

Second, we have the nbspWordMin variable to hold our minimum word count. It wouldn’t make sense to prevent a line break if the element only contains two words. I prefer to only start preventing line breaks when a string has six words or so, so I set the nbspWordMin variable accordingly:

var nbspWordMin = 6;

Third, we loop through each of the selectors and replace the final space in each element with a non-breaking space, provided that there are enough words in the element to meet our minimum word count setting.

Note for WordPress users

If you’re trying to quickly add this Javascript code (or any other Javascript code) to a WordPress site, consider using the Additional JS plugin. It creates a new “Additional JS” section in the customizer for adding Javascript code, and works much like the “Additional CSS” section that is built into WordPress.

Posted in

Leave a Comment

Your email address will not be published. Required fields are marked *