This script is very common and is used to count characters within textareas while the user is typing. Usually a textarea has a “keypress” event handler which updates relevant counter fields or spans. The easiest ways to fool this script is to drag-n-drop text into the textarea or by using a character map to insert special symbols into the textarea. Of course this is rare, but it is possible and believe me does happen. In such cases I prefer to use a different script that reduces these issues. The basic idea is to create a timer, which will periodically check circumstances and perform appropriate actions where needed. The script will check to see if there are any changes since last time it was run, before processing any data to increase performance.
var textarea;
function onloadhandler ()
{
textarea = document.getElementById("textarea-id");
if (textarea) {
textarea.oldvalue = textarea.value;
textarea.counter = document.getElementById("counter-id");
textarea.counter.innerHTML = "0";
setTimeout(ticker, 1);
}
}
function ticker ()
{
if (textarea && textarea.value != textarea.oldvalue) {
textarea.oldvalue = textarea.value;
textarea.counter.innerHTML = textarea.value.length;
}
setTimeout(ticker, 10);
}
This script tracks all possible changes made within a textarea input field, but it can be a little slow on some browsers and on computers with limited memory. What I suggest as a compromise is to use a combination of onkeyup event handlers and the same ticker function with increased time intervals. Let’s say one second. So, the final script should look like this:
var textarea;
function onloadhandler ()
{
textarea = document.getElementById("textarea-id");
if (textarea) {
textarea.oldvalue = textarea.value;
textarea.counter = document.getElementById("counter-id");
textarea.counter.innerHTML = "0";
textarea.onkeyup = ticker;
setTimeout(ticker, 1000);
}
}
function ticker ()
{
if (textarea && textarea.value != textarea.oldvalue) {
textarea.oldvalue = textarea.value;
textarea.counter.innerHTML = textarea.value.length;
}
setTimeout(ticker, 1000);
}
mmdesign
Thank you.