A jQuery "widon't" snippet

Share/Save

In the interest of more attractive Internets, here's a quick little javascript "widon't" snippet—written in jQuery—that I've been using. Now go do something cool with it.

jQuery(function($){
 
$('h1,h2,h3,li,p').each(
    function(){
        $(this).html($(this).html().replace(/\s([^\s<]+)\s*$/,'&nbsp;$1'));
    }
);
 
});

Feel free to replace or augment the selector ('h1,h2...p') with any additional elements you'd like to see widon'ted.

I actually use this variant, which lets longer words be widows if they wanna:

jQuery(function($){
 
$('h1,h2,h3,li,p').each(
    function(){
        $(this).html($(this).html().replace(/\s([^\s<]{0,10})\s*$/,'&nbsp;$1'));
    }
);
 
});

Note: Dave Cardwell posted a jQuery widon't a couple of years ago, but holy balls it's big... If you want something a bit more robust, be sure to check his out.

Another note: I added newlines and tabs to make the code more readable. If I were you, I'd remove those bad boys before deploying.

Update: I wrapped the snippets in a DOM ready callback, making it easier for those who just want to copy/paste these snippets into their site.

Comments

Nice one. Similar to my post last month: Three Quick Ways to Avoid Widows.

Finally! Been looking for something like this all day - works perfectly. Thanks.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li>
  • Lines and paragraphs break automatically.

More information about formatting options