jQuery WidowFix

What a terrible place to break

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eleifend diam non orci pellentesque sit amet scelerisque eros interdum. sInteger at sodales leo. Maecenas non felis nibh urna augue. Integer in urna ut erat ultricies rutrum. Cras eleifend metus laoreet lacus accumsan elementum augue aliquet orci diam.

WidowFix is a jQuery plugin to fix widows, or orphans, or whatever you call them—those single words on their own line. It does this by adding a   (non-breaking space) in between the last 2 words. It’s super lite and easy to use!

Download WidowFix on Github

How to Use

Attach jQuery:

<script type="text/javascript" src="path/to/jquery-1.4.2.min.js"></script>

Attach Widow Fix plugin:

<script type="text/javascript" src="path/to/jquery.widowFix-1.3.min.js"></script>

Call the widowFix method with your selector:

$(document).ready(function() {
//all heading 1s
  $('h1').widowFix();
//or specific h1s
  $('#mainColumn h1').widowFix();
});

That’s it! That will fix the widows.

Considering this is a client-side solution, I don’t recommend using the fix on every element, like $(‘p,h1,h2,h3,h4,h5,h6’).widowFix(); because that will have a performance hit (every ms counts). It will work, but I don’t recommend it.

Options

There are just 3 options, and you use them in this format:

$('h1').widowFix({
  letterLimit: 10,
  prevLimit: 5,
  linkFix: true
})

letterLimit will set the number of letters that you think still counts as a widow/orphan. Some people think that long words look fine by themselves and shouldn’t be Widow Fixed. So if you think words of 10+ letters look fine, set the limit to 10 and it will ignore those words. Any words shorter than 10 characters will still be fixed. The default is to fix all words regardless of characters.

prevLimit will set the ignore amount for the previous (second to last) word. If you don’t want to fix widows/orphans when the second to last word is shorter than 5 letters, set prevLimit: 5 and it will skip those widows. The default is to fix all words regardless of the previous word length.

If the last word in your element is a link, then it will replace the space between <a href>, giving you <a&nbsp;href>.The option linkFix: true will maintain your link and replace the proper space. Only add this option if this is a contant problem, as it will slightly slow down the script.

License and Credits

This plugin is dual licensed under the MIT and GPL licenses. It is partly based on Karl Swedberg’s post on widows. I reworked it a bit, added trailing space removal, letter counting, and the link fix. Feel free to use it in any projects, but please email me if you’re using it. I love to know where my projects are living.

Comments