For one of my web app projects, I needed a small component to display the number of characters being typed into a text field (a la Twitter). Unfortunately, I didn't think to check for any existing jQuery plugins for such functionality as there are quite a few. Fortunately, I just rolled my own and in the process finally realized the power of closures.
My implementation turned out to be:
this.AddCharacterCounter = function(textField, counterField, characterLimit)
{
var updateCounter = function()
{
// All the code here to count characters and set css styles
// based on whether or not the limit had been reached.
};
var handleKeyEvent = function(event)
{
updateCounter(textField, counterField, characterLimit);
};
textField.keydown(handleKeyEvent);
textField.keyup(handleKeyEvent);
updateCounter();
}
Then for any field that I wanted to attach such a counter, I just had to do the following:
that.AddCharacterCounter($('#field1'), $('#field1Counter'), 300);
that.AddCharacterCounter($('#field2'), $('#field2Counter'), 150);
that.AddCharacterCounter($('#field3'), $('#field3Counter'), 30);
No comments:
Post a Comment