Author: Steven Neiland

Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

At this stage we have our character count, but it would be nice if there was a visual way of alerting the user (ie me) to when the character limit has exceeded the desired length.

Step 3: Apply styling to countChars span depending on character count

We could use an alert box as a simple way of warning us when we enter too many characters but I find that to be too much of an interupt to my work flow, especially as I may actually want to enter a longer title than normal. Instead I favour changing the background colour of the character count to a primary colour such as red when the limit it exceeded. JQuery makes this really simple.

Lets create two style class's for the span. The first will be for when the character count is less than or equal to 70, and the second for counts above 70.

.countCharsOk {
padding:0 10px 0 10px;

.countCharsRed {
padding:0 10px 0 10px;

To apply the relevent css class's modify the script as follows.

<script type="text/javascript">
//every time user types in the blogTitle input field do the following
$('#blogTitle').keyup(function() {

//get the length of the input text value
var charLength = $(this).val().length;

//set the inner html of chountChars equal to charLength

//if charLength gt 70
if(charLength > 70) {
//remove all existing css class's from countChars
//then add the class 'countCharsRed'
} else {
//remove all existing css class's from countChars
//then add the class 'countCharsOk'
1 2 3

What Do You Think?

Reader Comments

Post a Comment

Comment Etiquette:

  • Please keep comments on-topic.
  • Please do not post unrelated questions or large chunks of code.
  • Please do not engage in flaming/abusive behaviour.
  • Comments that contain or appear to be advertisments, will not be published.
  • Comments that appear to be created for the purpose of linkbuilding to commercial sites will be removed.

We are all adults here so play nice.


Archives Blog Listing

Tag Listing

Learn CF In A Week


Fork me on GitHub