Home / Count the words in an FCKeditor instance with Javascript

Count the words in an FCKeditor instance with Javascript

A couple of days ago I looked at how to count the words in a textarea or input with jQuery and in this post look at how to do the same but for an FCKeditor instance. FCKeditor is an in-browser HTML editor. The code for counting the words uses regular Javascript and does not require jQuery.

Example

First of all here’s an example to show you it working. If you are reading this in an RSS reader you will need to click through to view this in a web browser for it to work.

 

Type some text into the above FCKEditor instance and the word count above it will change as you type.

The HTML

The only HTML required is the container for the word count:

<div id="word_count"></div>

The Javascript code

Here’s the Javascript to make the word count functionality work:

function FCKeditor_OnComplete(editorInstance) {
   
    fckeditor_word_count(editorInstance);
    editorInstance.Events.AttachEvent('OnSelectionChange', fckeditor_word_count);
   
}

function fckeditor_word_count(editorInstance) {

    var matches = editorInstance.GetData().replace(/<[^<|>]+?>|&nbsp;/gi,' ').match(/b/g);
    var count = 0;
    if(matches) {
        count = matches.length/2;
    }

    document.getElementById('word_count').innerHTML = count + " word" + (count == 1 ? "" : "s") + " approx";

}

FCKeditor_OnComplete() is triggered by the FCKEditor itself when it’s finished loading. The function defined above calls my fckeditor_word_count function to initialise the word count container with the current number of words and then attaches an event to the editor instance so whenever the selection is changed it calls the word count function again.

The word count function gets the HTML from the FCKEditor instance, strips out the HTML tags and non-breaking spaces and then matches word boundaries (this is covered in my previous post about word counting).

Finally, the word_count container is updated with e.g. “0 words approx”, “1 word approx”, “2 words approx” etc.

Browsers tested

I have tested the above code in IE6, IE8, FF1, FF3.5, Chrome 2. It worked in all of them testing with 9000 words generated from lipsum.com.

On my speedy machine with lots of RAM with the newer browsers there was really no difference between having the word counting on and off with 9000 words; on a virtual machine with 256MB on the older browsers it got fairly sluggish with 9000 words when word counting so it will pay to be careful enabling a function like this if you are editing large documents on older computers, because of the regular expressions being run on every keypress.

Note that as per the FCKeditor documentation “in IE, this event [OnSelectionChange] does not fire on every keystroke, but only on some random keystrokes.”