I need to add an event listener for keypress after the CKEditor is loaded.
The code is something like:
CKEDITOR.instances.editor1.document.on('key', function(event) {
/* instructions */
});
Any idea where can I add the code for that? In which file or in what way?
// Add event listener on keypress document. addEventListener('keypress', (event) => { var name = event. key; var code = event. code; // Alert the key name and key code on keydown alert(`Key pressed ${name} \r\n Key code value: ${code}`); }, false);
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.
The simple solution: just use the keyup event (and not the keydown event). This will give you the latest value after the user typed the latest character. That resolves the issue.
The keydown event is fired when a key is pressed. Unlike the deprecated keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.
Code to archive it is something like this:
CKEDITOR.on('instanceCreated', function(e) {
e.editor.on('contentDom', function() {
e.editor.document.on('keyup', function(event) {
// keyup event in ckeditor
}
);
});
});
Edit - 2014 - Since this answer is still getting some upvotes, i felt it would be fair to point out, that it was meant for CKEditor in version 3.x. With the version 4.x there is a change event, which will trigger not only on key events but also after pasting, undo, redo etc.
In code its something like this:
CKEDITOR.on('instanceCreated', function(e) {
e.editor.on('change', function (event) {
// change event in CKEditor 4.x
});
});
Do you need to track changes?
I was originally using the solution above, but I ended up replacing it with the OnChange CKEditor plugin. This is useful in some special cases - for example, if you add a link using the toolbar, keypress won't register anything.
Here's a code example, updated to use instanceCreated (install OnChange first):
CKEDITOR.on('instanceCreated', function(e) {
if (e.editor.name === editorId) { //editorId is the id of the textarea
e.editor.on('change', function(evt) {
//Text change code
});
}
});
Update: According to the answer above, CKEditor now has a built-in change event, so you don't have to install the plugin to use this solution anymore. You can still use the second line of code to apply the change to the instance of CKEditor you want to edit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With