Sorry friends on the way of move to new home I’ve been lost from the blog as I didn’t have internet connection for few last weeks. Now, I’m back and I try to be regular as much as I can. Inspired from the new feature of wordpress 2.6.x which displays word count of each post, I’ve developed jQuery plugin to display word-count of Textarea. Please note that it is word count plugin not character counter.
Jquery plugin: Word-count code
jQuery.fn.wordCount = function(params)
{
var p = {
counterElement:"display_count"
};
var total_words;
if(params) {
jQuery.extend(p, params);
}
//for each keypress function on text areas
this.keypress(function()
{
total_words=this.value.split(/[\s\.\?]+/).length;
jQuery('#'+p.counterElement).html(total_words);
});
};
As you can in the above code, I assume that each words of a paragraph are separated by the either spaces or dots(.) . Please have your suggestion if i can more characters to improve this plugin.
How to use this plugin?
Well, you can guess that a Textarea is needed of whose words are counted and another element like div or span needed to display the word count.
For example, the below HTML code contains Textarea (whose total word is counted) and span (for displaying counted word).
<textarea name="word_count" id="word_count" cols="30" rows="6"></textarea> Total word Count : <span id="display_count">0</span>
Remember that the id of text area is “word_count” and “display_count“.
Now, let look at the jQuery code for displaying word count of text area , note that we are calling the function wordCount() which we’ve just developed in the plugin of jQuery.
$('#word_count').wordCount();
Note: display_count is default id of element which is already defined in the plugin if you want to use the different id of elment then you’ve to override the value of variable counterElement which contains the id of element displaying word count.
$('#word_count').wordCount({counterElement:"word_counter"});
Posted in
Tags: