PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » jQuery » Add Non-Breaking Space on Title to Prevent Widows

Add Non-Breaking Space on Title to Prevent Widows

$("h2").each(function() {
         var wordArray = $(this).text().split(" ");
         var finalTitle = "";
         for (i=0;i<=wordArray.length-1;i++) {
            finalTitle += wordArray[i];
            if (i == (wordArray.length-2)) {
                finalTitle += "&nbsp;";
            } else {
                finalTitle += " ";
            }
          }
          $(this).html(finalTitle);
});

Turns this:
New Screencast: First Ten Minutes with TypeKit

Into this:
New Screencast: First Ten Minutes with&nbsp;TypeKit

Subscribe to The Thread

  1. You can actually do that without the inner loop like this:


    $("*").each(function(){
    var content,widow;
    content = $(this).text().split(" ");
    widow = " "+content.pop();
    $(this).html(content.join(" ")+widow);
    });

  2. whats the point??

    • James, in print typography (magazines, books, etc) it’s considered bad style to have a single word by itself on the last line of a paragraph, especially across columns, and single lines across pages. On the web it’s only started to be addressed with css.

      http://reference.sitepoint.com/css/orphans

  3. if you have an <a> inside of an <h2> you should change the .text() function with the .html() funtion for take the right wordarray.


    var wordArray = $(this).html().split(” “);

    It’s not really stable but works!

  4. Francesco

    this topic is very interesting especially if applied to the new fluid layout trend

  5. El garch Hicham

    I agree with Milovan the {white-space:nowrap} do that job

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~