Skip to content Skip to sidebar Skip to footer

Preventing Orphans

I am attempting to prevent single word orphans by adding a non breaking space between the last 2 words within paragraphs and headings. The script I am using however is having the s

Solution 1:

Try using html() instead of text():

$("p,h1,h2,h3,h4,h5,h6").each(function(i,e) {
  var text = $(e).html();
  text = text.split(' ');
  var lastWord = text.pop();
  text = text.join(' ') + " " + lastWord;
  $(e).html(text);
});

fiddle

Btw, there is one corner case it doesn't work for, and it's when last single word of element to be unorphaned is inside the <a>, or any other tag with attributes, like:

<p>Lorem ipsum dolor sit <ahref="">amet.</a></p>

Solution 2:

The problem is that you're using .text() which gets the combined text of the element and it's decedents, not the decedent elements themselves, so when you replace the HTML with something generated from this, it doesn't include them.

You might have better luck using .contents(), taking the last text node, and replacing that with a text node, an &nbsp; element and a text node representing the final word.

Solution 3:

functionnoMoreLonelyWords(selector, numWords){

      // Get array of all the selected elementsvar elems = document.querySelectorAll(selector);
      var i;
      for(i = 0; i < elems.length; ++i){

        // Split the text content of each element into an arrayvar textArray = elems[i].innerText.split(" ");

        // Remove the last n words and join them with a none breaking spacevar lastWords = textArray.splice(-numWords, numWords).join("&nbsp;");

        // Join it all back together and replace the existing// text with the new textvar textMinusLastWords = textArray.join(" ");
        elems[i].innerHTML = textMinusLastWords + " " +  lastWords;
      }
    }

    // Goodbye lonely wordsnoMoreLonelyWords("p", 2);
<divclass="onePar"><p>This is an example page. It’s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say
    something like this:
  </p></div><divclass="twoPar"><p>This is an example page. It’s different from a blog post because it will stay in one place and will show up in your site navigation (in most themes). Most people start with an About page that introduces them to potential site visitors. It might say
    something like this:
  </p></div>

Post a Comment for "Preventing Orphans"