Way 2 Web

Web development tips


 
Text Counter

Introduction

Text Counter limits the amount of text in a textarea or textbox, and indicates the amount of characters remaining by means of a customizable counter.

The counter element ID is a combination of the text area/texbox ID and the suffix "-Counter".

Use CSS to customize the appearance of the counter.

API

Constructor

TextCounter (targetTag, maxCharacters[, beforeText] [, afterText]);
targetTag
Object reference or ID of the Text Area of Textbox
maxCharacters
Maximum number of characters allowed
beforeText
Text to appear before the Counter tag. Default: "Chars left:"
tagID
Text to appear after the Counter tag. Default: ""
[Top of page]

Demo

1. Text Area

A text area with max 50 characters.

2. Textbox

A textbox with max 20 characters.

[Top of page]

Code

HTML

<textarea id="myTA">Existing text...</textarea>
<input type="text" id="myT" value="Existing Text..." />

Javascript

<script language="javascript" src="../../js/x/x_core.js"></script>
<script language="javascript" src="../../js/x/x_dom.js"></script>
<script language="javascript" src="../../js/x/x_event.js"></script>
<script language="javascript" src="../../js/y/ylib.js"></script>
<script language="javascript" src="../../js/y/y_util.js"></script>
<script language="javascript" src="../../js/y/y_TextCounter.js"></script>
<script language="javascript">
    window.onload = function(){
        var textA = new ylib.widget.TextCounter("myTA", 50);
        var textB = new ylib.widget.TextCounter("myT", 20, "", " chars left");
    }
</script>

CSS

#myTA-Counter {
    width: 100px;
    border: 0;
}
#myT {
    width: 195px;
    float:left;
}
#myT-Counter {
    width: 80px;
    height: 16px;
    float:right;
    border: 1px solid Green;
    text-align: right;
    padding: 0 2px 0 2px;
}
[Top of page]

Files

Updates

  • 05-Nov-2008 If you're using version 4.1 of X library, you'll need to add the following files (available from X library) to your page:

    • js/x/lib/xparent.js
    • js/x/lib/xdisplay.js
    • js/x/lib/xappendchild.js

    Thanks to Daniele for the tip off.

[Top of page]