jQuery Word-wrap Plugin

The Problem

When it comes to textareas, the concept of word-wrapping is not as easy as it should be. In most browsers, including Firefox, Safari, Chrome, and Opera, you can set the textarea’s wrap attribute to on or off to achieve your preference.  Internet Explorer, on the other hand, requires a special value for the wrap attribute.

Although it should be simple enough to check for the browser type and toggle the appropriate value for wrap on-the-fly, there’s one more problem.  Because it’s not technically a valid attribute, most browsers (other than IE) won’t respond to changes to the wrap attribute that occur via JavaScript.  This means that if you want to have a checkbox next to your textarea that enables and disables word-wrapping dynamically, you’re out of luck.

The Solution

To work around this problem, we need to first check for the browser type and go from there:

  1. If IE, update the wrap attribute to be either soft or off
  2. If not IE, clone the textarea, set the appropriate wrap attribute, and update the DOM

Here is a really simple jQuery plugin that I’ve created to do just that.

The jQuery Word-wrap Plugin

The plugin is really easy to use.  Just make sure to include jQuery and the plugin in your page:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.wordWrap.js"></script>

To enable and disable word-wrapping on-the-fly, simply call the wordWrap() method at any time:

$(document).ready( function() {

	// Enable word-wrapping
	$("TEXTAREA").wordWrap('on');

	// Disable word-wrapping
	$("TEXTAREA").wordWrap('off');

});

You can use any standard jQuery selector.   Note that browsers have word-wrapping enabled by default for textarea elements.

Demo

View a working demo of this plugin.

Download

Version 1.0

This plugin is provided to you as-is, at absolutely no cost. If you would like to support its development, feel free to contribute any amount you prefer via PayPal. As always, you are welcome to contribute code for bug fixes and feature enhancements as well. Either way, thanks for supporting our efforts!

Licensing & Terms of Use

This plugin is dual-licensed under the GNU General Public License and the MIT License and is copyright A Beautiful Site, LLC.

If you enjoyed this article, please share it with a friend!

Comments are closed.