O'Reilly

Pretty Word Wrapper with MooTools or PHP

By on  

Details, details, details. Details are what take a good site to the next level. Small details like link nudging (jQuery, MooTools), simple but stylish CSS enhancements, and opacity effects are the cheeky effects that give your website the edge over similar websites. The detail we'll be addressing today is "widowed" text. A "widow" occurs when only one word of a long string wraps to the next line. An example would be:

Widow

No offense to raging cougars out there but widows look wonky. The best way to prevent widows is to add a " " between the last and second-to-last words in a string. Doing this, the example above would split to the next like at "or" so that two words would be on the second line. Today I'll show you how to accomplish this using a tiny MooTools class or PHP.

The MooTools JavaScript

//class
var WordWrapper = new Class({
	
	Implements: [Options],
	
	options: {
		elements: 'h1',
		minWords: 3
	},
	
	initialize: function(options) {
		this.elements = $$(options.elements);
		this.elements.each(function(el) {
			this.apply(el);
		},this);
	},
	
	apply: function(element) {
		var original = element.get('html'), arr = original.split(' ');
		if(arr.length >= this.options.minWords) {
			//join the last and second to last
			arr[arr.length - 2] += ' ' + arr[arr.length - 1];
			arr.pop();
			element.set('html',arr.join(' '));
		}
	}	
});

The MooTools plugin offers just a few options: the elements to apply this too and the minimum number of words the element must have before the substitution takes place. The usage is just as easy as you'd expect:

//usage
window.addEvent('domready',function() {
	var ww = new WordWrapper({
		elements: 'h2'
	});
});

//sample results
//"This Is The First Attempt" becomes: This Is The First Attempt
//"Leave Me" is not long enough to modify
//"Que?" is not long enough to modify
//"I Am, I Am SuperMan, And I Can Do Anything" becomes: I Am, I Am SuperMan, And I Can Do Anything

Awesome....but what about a PHP version? Sure, why not?

The PHP

function word_wrapper($text,$minWords = 3) {
	$return = $text;
	$arr = explode(' ',$text);
	if(count($arr) >= $minWords) {
		$arr[count($arr) - 2].= ' '.$arr[count($arr) - 1];
		array_pop($arr);
		$return = implode(' ',$arr);
	}
	return $return;
}

And Voila! Now you can update any text before it hits the DOM!

The jQuery

Wanna see how you'd accomplish this feat with jQuery? Hop over to Chris Coyier's CSS-Tricks blog post to find out!

O'Reilly Velocity Conference
Save 20% with discount code AFF20

Recent Features

  • Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() – this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

Incredible Demos

  • TextboxList for MooTools and jQuery by Guillermo Rauch

    I'll be honest with you: I still haven't figured out if I like my MooTools teammate Guillermo Rauch. He's got a lot stacked up against him. He's from Argentina so I get IM'ed about 10 times a day about how great Lionel...

  • RealTime Stock Quotes with MooTools Request.Stocks and YQL

    It goes without saying but MooTools' inheritance pattern allows for creation of small, simple classes that possess immense power.  One example of that power is a class that inherits from Request, Request.JSON, and Request.JSONP:  Request.Stocks.  Created by Enrique Erne, this great MooTools class acts as...

Discussion

  1. Chris the Developer

    Wouldn’t it be more safe-mode friendly if you used document.getElements() instead of $$?

  2. @Chris the Developer: How so?

  3. Francis

    Took me a while to understand what this was doing until I noticed that the &nbsp is replaced by a blank space ‘ ‘ in the code!
    Should read: $arr[count($arr) – 2].= ‘&nbsp’.$arr[count($arr) – 1];

  4. Thanks Francis! Stupid WordPress…

  5. Ineresting approach, I use a little function that cuts the text off after a certain amount of characters and then adds … to it. Of course I’m checking correctly for things like, cutting at the first space before the max amount of chars, taking care of commas and hyphens, etc

  6. Dutchie

    Hmm.. I like this idea, but still the www is not a thing like print is in combination with InDesign (I reffuse to mention Quark, lol), which have advanced widow cut rules etc. build in. I mean, it’s not always appropriate to move the two last words to the next line as a default in various languages/situations.. then I rather blame the browser’s neanderthaler rudeness :)

    But again, it’s an original idea which probably makes the headlines in most cases a bit nicer, and the JS is small (and php is fast).

  7. Greg

    You can stream line you code a little by changing the

    arr[arr.length - 2] += ' ' + arr[arr.length - 1];
    arr.pop();
    

    with

    arr[arr.length - 2] += ' ' + arr.pop();
    

    You can do the same with the PHP too.

    since the array Pop method both removes the last item in the array AND returns its value. Though this will not make a huge impact on the performance of the code it is code practice.

  8. Simon

    I can’t get this to work. Am I doing something wrong?

    I add the php code into the head but it doesn’t add a non-break-space

    Can anyone point me to a working example?

    • Works fine for us with PHP, example in the h1 headline at http://charleston.thedigitel.com/politics/folly-beach-bans-discrimination-based-sexual-orien-38425-0315

      I also modified it a bit to allow for us to concat the last three words if there are six or more words (good for our headline setup), code below.

      /**
       * Prevent widows
       * based off http://davidwalsh.name/word-wrap-mootools-php
       *
       * If there are 6+ words it will concat three words with ' '
       * otherwise if 3+ it will concat two words at end
       *
       * The longWords can be disabled by setting $longWords 
       * to a high value (i.e. 99999) when calling the function
       * 
       **/
      function word_wrapper($text,$longWords = 6,$minWords = 3) {
        $return = $text;
        $arr = explode(' ',$text);
        if(count($arr) >= $longWords) {
          $arr[count($arr) - 2].= ' '.$arr[count($arr) - 1];
          array_pop($arr);
          $arr[count($arr) - 2].= ' '.$arr[count($arr) - 1];
          array_pop($arr);
          $return = implode(' ',$arr);
        } elseif(count($arr) >= $minWords) {
          $arr[count($arr) - 2].= ' '.$arr[count($arr) - 1];
          array_pop($arr);
          $return = implode(' ',$arr);
        }
        return $return;
      }
       
       
  9. Fiddlesticks, it garbled my code paste (I even used the tags!) See it here http://pastebin.com/DhVKZu1T

  10. Okay, I give up. Here is a Gist on how to do it in Ruby: https://gist.github.com/stephenhowells/6245701“>https://gist.github.com/stephenhowells/6245701″ rel=”nofollow”>https://gist.github.com/stephenhowells/6245701

  11. Andrew Zammit

    I believe this should be done on the front-end, however here’s an alternate PHP implementation (no support for min words):

    function noWidow($str) {
        return preg_replace('/\\s+([^\\s]+\\s*)$/',' $1',$str);
    }
    
  12. Andrew Zammit

    I believe this should be done on the front-end, however here’s an alternate PHP implementation (no support for min words): http://pastebin.com/0h6ZqZUE

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Prevent Chrome from Translating a Page

    A while back I shared my favorite Google Chrome extension:  Google Art Project.  I've enjoyed seeing beautiful art when I open a new tab -- it's brought genuine happiness to my day, however small that happiness may be.  About a week ago, however, the art presented had...

  • Create Any Type Of Website With These Multi-Purpose Themes

    We have selected what we believe are the very best multipurpose WordPress themes on the market today. Our list contains a number of best sellers, several newcomers that are proving to be highly popular, and a few themes that are ideal for creating the types of...

  • An Introduction to Static Site Generators

    Static site generators seem to have been becoming more and more popular recently, but they’re not one of those ephemeral novelty things that grow in popularity as quickly as they fall into oblivion shortly after. For over a decade, many different projects — 394 of...

  • Automated Tests for Visual Responsive Layouts

    Today it's all about testing. In 2015, many developers knows about TDD and I personally think that testing is one of the key for quality products. But what about testing in a Front-end environment? How do you guys write your tests for a responsive page or...

  • Getting Dicey With Flexbox

    What if you could build complex CSS layouts in minutes? Flexbox is a new CSS layout spec that makes it easy to construct dynamic layouts. With flexbox, vertical centering, same-height columns, reordering, and direction agnosticism are a piece of cake. There's a popular myth floating around that...