I have a textbox, and everytime the user presses a key, I compute the field’s new length to see how many characters are still available.
Based on that number, I :
- check if the “send” button should be enabled or not
- check if the counter that displays the length should be red or black (à la twitter)
But now I have a problem; on each keydown event, I do :
remaining = 100 - count;
if (remaining > 9)
{
//blue counter; send is activated
//"if counter.class == red then counter.class = blue..."
//"send.off('click'); send.on('click', sendmessage)..."
}
else if ((remaining <= 9) && (remaining >= 0))
{
//red counter; send is activated
}
else //remaining <0
{
//red counter; send is deactivated
}
Each time the user presses a key, one of the 3 blocs is executed… Isn’t there a way to execute the blocs only when the variable changes “zone” ( ]∞, 9[; [9,0]; ]0; -∞[) ?
No doubt this could be done more elegantly, but the simple answer is just to remember the previous value of the length:
Initialise
prevCountto whatever value makes sense when the screen loads…(P.S. How can the count be less than zero?)
Update: Since you’ve confirmed that you’re using jQuery you could do something like this (assumes “black” and “red” are classes in your stylesheet with the appropriate colours and formatting setup):
Disables the send button if there’s no text or too much text; changes the class from black to red only when necessary. (You could also make black the default and just toggle the “red” class on and off.)
Demo: http://jsfiddle.net/ZAjez/