Aaron Turecki
Aaron Turecki

Reputation: 355

CKEditor - grab content from editor to setup live total word count

I'm trying to access the live content from each instance of CKEditor so I can setup a total word count. Before using CKEditor I would get the textarea's content with .getElementById(), and then I would get the live word count by passing the textarea element into my Countable() function which appends an event listener to the area. Is there a way to grab the live content of a CKEditor instance? I know it's an iframe so I'm not sure if it's possible to grab the live content.

Code I used to use with simple textarea:

var area1 = document.getElementById('textarea1');
    Countable.live(area1, function(counter1) {
        jQuery("#word_count1").text(counter1.words);
        a1_count = counter1.words;
        total_count();
    });

Upvotes: 0

Views: 459

Answers (1)

Joel Peltonen
Joel Peltonen

Reputation: 13412

This depends a lot on your Countable function and it's requirements - it would have helped to seen it and to know it's requirements. You can get the contents of each CKEditor instance in a few different methods, this is one

var contentArray = [];
var i = 0; 
for (var instance in CKEDITOR.instances) { 
    var tmpEditor = CKEDITOR.instances[instance]; 
    contentArray[i] = tmpEditor.getData(); 
    i++;
}

Now the contents are in the contentArray. But form your code it looks like Countable needs an element. I'm unsure as to what kind of element reference it can use, but something like this might get you further:

var editor = CKEDITOR.instances.editor1; // change "editor1" to suit your editor
var element = editor.editable().$; // Get a reference to the body of the instance
Countable.live(element, function(counter1) {
    jQuery("#word_count1").text(counter1.words);
    a1_count = counter1.words;
    total_count();
});

Now of course this only supports one editor instance, but the two examples combined might do the trick. Hopefully you don't use inline instances (it needs some additional work but is doable). Also note that naturally these return the source, not the text.

Also not that you do not want to loop this very quickly, it is very cpu intensive. I recommend a slow loop combined with the the CKEditor change event and maybe some other events that trigger the update. Do not trigger on every change, rather set a timeout to buffer the update trigger (you don't want to do the update when the user is typing).

Upvotes: 1

Related Questions