jQuery Plug-in: Characters Left

There have been a couple of recent projects that have needed a Twitter style character count down function. Since I seem to keep using the function I thought I’d make a little jQuery plug-in that does the same job (demo).

1
2
3
4
5
6
7
8
9
10
11
12
//Plug-in usage
jQuery(function($){//jQuery ready
    $("#myTextarea").charsLeft({
        maxChars: 100,
        attachment: "before",
        charPrefix: "You have",
        charSuffix: "characters left.",
        wrapperClass: "charsLeft",
        countClass: "charCount",
        errorClass: "charError"
    });
});

The plug-in has a few options that can be controlled when implimenting:

  • maxChars: Maximum number of characters a user can enter (default: 100).
  • charPrefix: The text that comes before the character count (default: “You have”).
  • charSuffix: The text that comes after the character count (default: “characters left.”).
  • attachment: How the paragraph is attached to the input / textarea. Accepts “before” and “after” (default: “after”).
  • wrapperClass: The class applied to the wrapper div (default: “charsLeft”).
  • countClass: The class applied to the number count span (default: “charCount”).
  • errorClass: The class applied to the input / textarea when a user goes over allowed number of characters (default: “charError”).

An example of the HTML that is added to the input / textarea:

1
<div class="charsLeft">You have <span class="charCount">100</span> characters left.</div>

Note: This plug-in doesn’t stop a user from submitting a form when they are over the maximum number of characters, it is simply for visual feedback.

View a demo (version 0.1 – updated 5th Feb 2010).