Monday, June 20, 2011

How to attach CKEditor keyup event

My current version: CKEditor 3.6

  editor.document.on('keyup', function(evt){...});

I am trying to attach a keyup event to CKEditor. Unfortunately, it doesn't fire as soon as the setData() is being called.

It turns out that the editor.document is recreated every time setData() is called and thus all the events attached to the editor.document will be gone forever. Re-attaching the event to the editor.document is necessary. Luckily, setData() supports callback.

  editor.setData('set some data', function(evt) {
    editor.document.on('keyup', myKeyupEvent);

I don't understand why CKEditor won't support keyup event in editor.on. You can't do this:

err editor.on('keyup', function(evt){...});

But for keypress or keydown event, you can do this:

  editor.on('key', function(evt){...});

There isn't much details about the CKEditor event. Their API isn't helpful either. Reading through the event API, I still have no idea when I should be able to use editor.on to attach events and when I should use editor.document.on.

What I understand is that editor.on is good for custom events. You write your own event, hook it up and then fire it up yourself as needed. The events registered by editor.on will not be removed after setData() has been called. It means that there is no need to re-attach the event even though the editor.document is re-created.

For events registered by editor.document.on, they support all existing defined events as long as you provide a event handler for them. The drawback is that the event handler requires registration again after editor.document has been recreated.

Currently, I have no custom events to be defined; thus, I found editor.document.on more useful than editor.on. I can hook as many events I want without restrictions.


  1. Thanks for your post, I was having a really hard time handling the keyup event until I found this. I don't know why nobody mentions the fact that the document object is destroyed the way you explained.

  2. OMG thank you very much. YOur post have solved all my doubts. You saved me a lot of time.