[jQuery] How to remove orphans from text by Javascript/jQuery?

Data dodania wpisu: 09-11-2010

Quite often we meet up with websites that have "orhpans" in text or single chars on the end of a textline. Some languages grammar rules reccomend to avoid such practices. But the problem is not the text, but its visual presentation in webbrowsers.

How do I remove this bad behavior?

It's quite simple to do this in webbrowsers, moreover - search engines won't apply this jQueryfied tricks to it's site cache. The solution is to insert a hard space ( ) in your HTML code after every single char and before the next word (between both of these ones) by replacing it's natural space char. This solution will automatically take every single char beeing connected with a next words and beeing moved to the next textline.

All the solution job is done by a very short & easy jQuery plugin:

Plugin code:

(function($){
    $.fn.removeOrphans = function(){
        if($(this).length > 0) {
            var $html = $(this).html();
            $html = $html.replace(/(\s)([\S])[\s]+/g, "$1$2 ");
            // using regexp to every single char
            // having spaces before and after of its
            // we replace a space with a hard space -  
            // which - naturally - merges this char with the next word / char etc.
             $(this).empty().html($html);
        }
    }
})(jQuery);

And the plugin calling examples:

$(document).ready(function(){
    $('#content').removeOrphans();
    $('#content1, #content2, #content3').removeOrphans();
});

Regards and have a nice fun with divs torturing by the plugin;)

Comments

This entry has no comments yet

Comments closed...

DesignEnd on Facebook

Inspiration