Character countdown like on twitter

argon picture argon · Jan 26, 2010 · Viewed 48k times · Source

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

Answer

Brian McKenna picture Brian McKenna · Jan 26, 2010

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.