I am currently working on new features for this site, but I wanted to put something up. So today I am going to cover a simple little JQuery script that I installed in my blog entry system. Anyone with more than basic knowledge of JQuery can skip this one.
When creating my blogs I do a couple of things for SEO. One of those things is to ensure that my blog title is not longer than 70 characters. I dont make this a hard rule only a guideline. To save me having to count the characters manually or using a document editor like Word, I wrote a simple JQuery script to count the characters and apply some styling when I go over the character limit.
In order to display the characters count, create a span next to the "Blog Title" input field and give it an id of "countChars".
The next step is a simple matter of adding a keyup listener to the blogTitle input which counts the number of characters and outputs it to the display container.
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.
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 {
color:#000;
padding:0 10px 0 10px;
}
.countCharsRed {
color:#fff;
background-color:red;
padding:0 10px 0 10px;
}
To apply the relevent css class's modify the script as follows.
At this stage the script is working perfectly apply and removing the css class's and updating the character count. Only one thing remains and that is to run the script on initial page load. This is necessary if we are editing an existing post and want to see the character count when the form loads. We could do this part server side but it is not necessary, all we need to do is call the keyup event once when the form is finished loading.
So there you have it, a simple script to count the characters in an input box and give us a visual alert when.