How to Improve HTML Heading Layout with jQuery

When headings marked-up with the <h1>, <h2>, … <h6> HTML tags are too long to fit on a single line, web browsers wrap the trailing words onto the next line. When the second line of the heading contains two or more words, this layout looks fine. However, when the second line contains just a single word, this layout is ugly—to my eye at least.

For example, I would prefer my browser wrapped the last two words of the title of this article, How to Improve HTML Heading Layout with jQuery, rather than just the last word:

Bad How to Improve HTML Heading Layout with
jQuery
Good How to Improve HTML Heading Layout
with jQuery

Clear heading layout is important because users scan web pages so quickly. The typesetting industry doesn’t like straggling words either; authors, editors and typesetting software make sure that books and other printed documents don’t contain widows and orphans, which are paragraphs that begin on the last line of a page or end on the first line of a page.

The solution to a lone word on the second line of an HTML heading is itself simple: replace the space between the last two words in the heading with the non-breaking space entity (&nbsp;) to force browsers to wrap the last two words of the heading onto the next line. The real work is how to insert the &nbsp; into the heading.

If you’re coding your own website, it’s easy to insert the &nbsp;, either by replacing the last space in your headings in a text editor for static pages, or by amending the code that delivers your headings when you’re generating your website dynamically with PHP, for example.

If you’re using a content-management system like WordPress, it’s not so easy. Although WordPress themes format posts, pages and comments, themes use core WordPress functions that perform standard tasks, which include retrieving headings. Scouring the PHP files that implement WordPress to find the right place to insert the &nbsp; is time-consuming and boring. And besides, once you’ve fixed the layout of your WordPress headings, umpteen other publishing platforms await their own heading-layout fix. There has to be an easier way.

One of the nice things about the jQuery JavaScript library is the way it enables web browsers to implement simple solutions to problems that would require complex or time-consuming coding if implemented by web servers. By moving the responsibility for solving the heading-layout problem from the web server to the web browser, we can tweak the HTML headings with jQuery after the page has downloaded.

I wrote the joinLastTwoWords JavaScript function to join the last two words of any HTML element represented by the jQuery selector, which is passed in as the single parameter. Here’s the code:

// Start the standard jQuery closure
(function($) { $(document).ready(function() {

    function joinLastTwoWords(selector) {

        // Loop through each HTML element that matches the selector
        $(selector).each(function() {

            // Get the text marked-up in the currently selected HTML element
            var html = $(this).html();

            // Get the position in the text of the last space
            var pos = html.lastIndexOf(' ');

            // Only process HTML elements with a space
            // (i.e. with more than one word)
            if (pos != -1) {

                // The parts array stores the three parts of the new text
                var parts = [], i = -1;

                // The first part stores the text up to the space
                parts[++i] = html.substring(0, pos);

                // The second part stores the non-breaking space entity
                parts[++i] = '&nbsp;';

                // The third part stores the text after the space
                parts[++i] = html.substr(pos + 1);

                // Replace the text of the HTML element with a new
                // string created by joining the three parts
                $(this).html(parts.join(''));
            }
        });
    }

    // Join the last two words of text marked-up in HTML tags <h1> to <h6>
    joinLastTwoWords('h1, h2, h3, h4, h4, h6');

// End the standard jQuery closure
}); })(jQuery);

The joinLastTwoWords function loops through each HTML element selected by the jQuery selector string, which in this case is every element marked-up with any of the six HTML heading tags ('h1, h2, h3, h4, h4, h6').

If the text of the HTML element doesn’t contain a space, the loop moves on; otherwise the position of the last space is recorded (the last space separates the last two words).

The code then sets up a three-element array to contain all the words in the text before the space, the non-breaking space entity (&nbsp;), and the single word after the last space. The code then joins these three parts to form a new string which replaces the text of the HTML element.

To include the joinLastTwoWords function in your own website, you’ll need to save it in a file, upload it to your server and reference it in your HTML code. You’ll also need to include the jQuery library file (version 1.3.2 or later). Here’s an example:

<script type="text/javascript"
    src="https://yourdomain.com/js/join-last-two-words.js">
</script>

<script type="text/javascript"
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>

Because the joinLastTwoWords function runs after the browser renders the text, users may notice the titles being reformatted. However, users will likely consider this reformatting as part of the overall page-downloading process because images often cause multiple page re-layouts.

Download

Download the join-last-two-words.js script from GitHub.