Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript to avoid widows [duplicate]

A common problem when working with typography in HTML/CSS is something we call "horunge" in Swedish ("widow" in english).

What it is:

Let's say you have a box with a width of 200px and with the text "I love typograpy very much". Now the text breaks and becomes:

I love typography very
much

As a designer I don't want a word bastard (single word / row). If this was a document/PDF etc. I would break the word before very and look like this:

I love typography
very much

which looks much better.

Can I solve this with a CSS rule or with a javascript? The rule should be to never let a word stand empty on a row.

I know it can be solved by adding a <br /> but that's not a solution that works with dynamic widths, feed content, different translations, browser font rendering issues etc.

Update (solution) I solved my problem with this jquery plugin: http://matthewlein.com/widowfix/

like image 385
Emil Avatar asked Sep 16 '11 12:09

Emil


2 Answers

A simple jQuery / regrex solution could look like the following, if you add the class "noWidows" to the tag of any element that contains text you are worried about.

Such as:

<p class="noWidows">This is a very important body of text.</p>

And then use this script:

$('.noWidows').each(function(i,d){
   $(d).html( $(d).text().replace(/\s(?=[^\s]*$)/g, "&nbsp;") )
});

This uses regex to find and replace the last space in the string with a non-breaking character. Which means the last two words will be forced onto the same line. It's a good solution if you have space around the end of the line because this could cause the text to run outside of an element with a fixed width, or if not fixed, cause the element to become larger.

like image 77
jsdiamond Avatar answered Oct 03 '22 18:10

jsdiamond


Just wanted to add to this page as it helped me a lot.

If you have (widows) actually should be orphans as widows are single words that land on the next page and not single words on a new line.

Working with postcodes like "N12 5GG" will result in the full postcode being on a new line together but still classed as an orphan so a work around is this. (changed the class to "noWidow2" so you can use both versions.

123 Some_road, Some_town, N12 5GG

$('.noWidows2').each(function(i,d){ 
    var value="&nbsp;"
    $(d).html($(d).text().replace(/\s(?=[^\s]*$)/g, value).replace(/\s(?=[^\s]*$)/g, value)); 
}); 

This will result is the last 3 white spaces being on a new line together making the postcode issue work.

End Result

123 Some_road,
Some_town, N12 5GG
like image 43
Sam Miller Avatar answered Oct 03 '22 20:10

Sam Miller