Character countdown like on twitter

How can I make a "remaining characters" countdown like the one on Twitter with jQuery? And also limit the input to a textarea.


Make a span and textarea and give them unique selectors (using an ID or class) like so:

<textarea class="message" rows="2" cols="30"></textarea>
<span class="countdown"></span>

And then make an update function like so:

function updateCountdown() {
    // 140 is the max message length
    var remaining = 140 - jQuery('.message').val().length;
    jQuery('.countdown').text(remaining + ' characters remaining.');
}

And make that function run when the page is loaded and whenever the message is changed:

jQuery(document).ready(function($) {
    updateCountdown();
    $('.message').change(updateCountdown);
    $('.message').keyup(updateCountdown);
});

Visit an example and view the source. jQuery makes things like this very simple.


I've used Aaron Russell's simply countable jQuery plugin with success; though, if I were to have written it, I would have designed it a bit differently (automatic counter div creation, using a data-maxlength attribute instead of a plugin option, etc).

Simple usage:

$('#my_textarea').simplyCountable();

Advanced usage:

$('#my_textarea').simplyCountable({
    counter: '#counter',
    countable: 'characters',
    maxCount: 140,
    strictMax: false,
    countDirection: 'down',
    safeClass: 'safe',
    overClass: 'over',
    thousandSeparator: ','
});

It's a suicide to use jQuery, Mootools or similar for such simple task ... unless you are already using them for something else.

Simple javascript function:

function limitTextCount(limitField_id, limitCount_id, limitNum)
{
    var limitField = document.getElementById(limitField_id);
    var limitCount = document.getElementById(limitCount_id);
    var fieldLEN = limitField.value.length;

    if (fieldLEN > limitNum)
    {
        limitField.value = limitField.value.substring(0, limitNum);
    }
    else
    {
        limitCount.innerHTML = (limitNum - fieldLEN) + ' charachter(s) to go.';
    }
}

The first parameter is id of the input/textarea. The second - id of the div to display characters left. The third is the limit itself.

And simple HTML:

<input type="text" value="" name="title" id="title" maxlength="100" onkeyup="limitTextCount('title', 'divcount', 100);" onkeydown="limitTextCount('title', 'divcount', 100);">
<br>
<div id="divcount">100 charachter(s) to go..</div>