I maintain the Textfield Counter module. An issue was raised that the module does not work for textareas with CKEditor enabled. I need to catch a keyup event from editors, or even just the CKEditor module, for the module to work. I haven't worked much with Drupal editors, nor CKEditor. Does anyone have any insight into how to do this?

Comments

Jaypan’s picture

Well, once again I've come up with my own answer, though it's not really the one I wanted.

First off, it does not appear that there is any Drupal JavaScript API for interacting with editors. So I had to go directly to the CKEditor API to capture the key up event.

This is the code I was eventually able to use:
 

CKEDITOR.on('instanceReady', function () {
  // Get the HTML ID of the textarea input that would be used if the editor were not enabled:
  var fieldID = $(".some_textarea").attr("id");
  if (CKEDITOR.instances[fieldID]) {
    // Add keyup listener.
    CKEDITOR.instances[fieldID].on("key", function () {
      // The last key pressed isn't available in editor.getData() when
      // the key is pressed. A workaround is to use setTimeout(), with no
      // time set to it, as this moves it to the end of the process queue,
      // when the last pressed key will be available.
      var editor = this;
      window.setTimeout(function () {
        var text = editor.getData();
        // Do something with the text.
        // Also note that the original textarea can be
        // retrieved from editor.element.$. So you could
        // do this:
        var originalTextarea = editor.element.$;
      });
    });
  }
});