A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »
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 oroff to achieve your preference. Internet Explorer, on the other hand, requires a special value for the wrapattribute.
Although it should be simple enough to check for the browser type and toggle the appropriate value forwrap 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:
- If IE, update the wrap attribute to be either soft or off
- 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
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!
