Site icon Denis Bouquet

Avoid widows and orphans in copy using JavaScript

The classic question of designers, “is there anything we can do to make sure we don’t get ‘widows’?” This means no orphan word alone in the last line of the copy. With responsive design, and working with CMS (even static build), the only way to ensure the copy never ends up with what we call widows or orphans is to use JavaScript.

How to use JavaScript to remove widows and orphans in text on webpages

Some people also calls this single line words as “runts”. You can create a little function to use the CSS class white-space: nowrap;

The function I use with jQuery:

$('.last-words-nowrap').each(function() {
	const text = $(this).text();
	const words = text.split(' ');
	const totalWords = words.length;

	// Ensure there are at least 2 words
	if (totalWords >= 2) {
		const formattedLastWords = `<span style="white-space: nowrap;">${words[totalWords - 2]} ${words[totalWords - 1]}</span>`;
		const newText = text.substring(0, text.length - (words[totalWords - 2].length + words[totalWords - 1].length + 1)) + formattedLastWords;
		$(this).html(newText);
	}
});

Or in vanilla JavaScript:

const elements = document.querySelectorAll('.last-words-nowrap');

elements.forEach(element => {
	const text = element.textContent;
	const words = text.split(' ');
	const totalWords = words.length;

	// Ensure there are at least 2 words
	if (totalWords >= 2) {
		const formattedLastWords = `<span style="white-space: nowrap;">${words[totalWords - 2]} ${words[totalWords - 1]}</span>`;
		const newText = text.substring(0, text.length - (words[totalWords - 2].length + words[totalWords - 1].length + 1)) + formattedLastWords;
		element.innerHTML = newText;
	}
});

Tada! That should help fight these repetitive comments.

Adapt as you need.

You can improve the code by avoiding applying inline CSS with the style attribute in the HTML. Just make a class. Ie: .words-nowrap

Add this to your CSS

.words-nowrap {
    white-space: nowrap;
}

That’s better :)

Exit mobile version