Archive for December, 2012

Textarea Dynamic MaxLength jQuery Plugin

Tuesday, December 11th, 2012

I needed to set the max length of a textarea, but the textarea size was not known beforehand.  That is, some textareas might be large, some might be small, and there was no way to know what size they were.

Since the textareas were part of a situation where the form was absolutely positioned, it was imperative that the user could not enter more information than the textarea size.

Note that modern browsers allow you to resize a textarea – this can be overcome with some simple css:

textarea {
    resize: none;

Now that the textarea size is fixed, I just need to limit the amount of text the user can enter, so that it doesn’t overflow the given space.

All of the javascript solutions out there assumed a predefined maxlength for the textarea.  But that’s a bit problematic, too – most fonts aren’t fixed-width, which means that some letters take more space than others.  I wanted to allow completely dynamic, automatic calculation of the space required, and limit the text based on that real information.

So, using some creative programming, I’ve developed a jQuery plugin that can determine the dynamic maximum size of the textarea, and limits the user input to that maximum length.

The code is simple to use. Just include the script file (there’s a link for you below), and then call the following line:

jQuery(function($) {

And voila! Your textareas magically will limit the amount of text to just the text that fits within the textarea.

How it works

Some of you are going to want to know how it works.  Here you go:

The plugin detects the key-up stroke in a textarea.  When the keyup takes places, it does the following:

  1. It creates a hidden div (off screen) with the same size, shape, and font properties as the textarea.
  2. It adds the text from the textarea to that div
  3. It compares the height of the hidden div (which is allowed to stretch vertically) to that of the textarea.
  4. If the hidden div is taller than the textarea, it trims characters off the end of the input until the height is no longer too tall.
  5. Once the focus has left the textarea (on blur), it removes the div from the DOM.