Article  |  Development

CKEditor and Word Counts

Reading time: Less than a minute

Tip to add word counts to CKEditor

In a project we're currently working on, we created a form builder that could publish complex forms that include features such as:

  • Logic that can be applied to different fields, sections and pages
  • Configurable validations
  • Word counts by field, section or complete form
  • Option to allow some textareas to have WYSIWYG content

For word counting, we added a keyup handler on a class applied to text areas. This sends the element and its content off to the manageWordCounts function that calculates the word count of the content and displays this for the user to see.

$(".word-count").keyup(function() {
  manageWordCounts($(this), $(this).val());

Allowing text areas with WYSIWYG content presented a problem, as we use CKEditor to handle these. The interesting thing with CKEditor is that it hides your original text area and shows completely different content. In the background, it leaves your textarea exactly as it was when loaded up, and does not apply new content to it.

CKEDITOR.on("instanceReady", function(event) {
  var editor;
  editor = event.editor;
  return editor.document.on("keyup", function(event) {
    var content, element;
    content = editor.getData().replace(/<[^>]*>|/g, '');
    element = $('textarea#' +;
    return manageWordCounts(element, content);
  • When an instance of the editor is ready, we add a keyup handler to the editor.document. When a keyup event triggers...
  • Get the CKEditor content, and strip HTML from it
  • Find the original, hidden textarea
  • Update this textarea with the new content
  • Pass the element and its content off to the manageWordCounts function

This approach gives us a way to cleanly handle the management of word counts across different sources as all calculations are based off textarea elements.

The result of this can be seen here:


Have a project that needs help?