简体   繁体   中英

KeyDown event for CKeditor

In my application I have an instance of a CKEditor. While the user is entering text into the editor the first latter should be in uppercase. For that I wrote a jQuery keydown event handler, like this:

$(document).ready(function () {
    CKEDITOR.instances.CKEditor1.on('contentDom', function () {
        CKEDITOR.instances.CKEditor1.document.on('keydown', function (event) {
            if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey) && !(event.ctrlKey) && !(event.metaKey) && !(event.altKey)) {
                var $t = $(this);
                event.preventDefault();
                var char = String.fromCharCode(event.keyCode);
                $t.val(char + $t.val().slice(this.selectionEnd));
                this.setSelectionRange(1, 1);
            }
        });
    });
});

It gives an runtime error ie,

0x800a138f - JavaScript runtime error: Unable to get property 'on' of undefined or null reference

How can I create keydown event for ckeditor.(the above code I wrote in .aspx page)

You can achieve this with the following code.

 CKEDITOR.replace( 'editor1', {
        on: {
            instanceReady: function() {
                alert( this.name ); // 'editor1'
            },

            key: function() {
                setTimeout(function(){
                    console.log('key pressed');
                },1);
            }
        }
    });

Without the setTimeout function the editor cannot capture the last key pressed.

CKEditor version 4.x

I believe you're registering the contentDom event the wrong way. To instantiate CKEDITOR and register the contentDom event you'd do

   CKEDITOR.replace( 'editor1', {
    on: {
        instanceReady: function() {
            alert( this.name ); // 'editor1'
            var editor = this;
            editor.on( 'contentDom', function() {
              var editable = editor.editable();
              editable.attachListener( editable, 'click', function() {
                console.log( 'The editable was clicked.' );
              });
           });
        }
    }
} );

Your code is trying to access the CKEDITOR instance before it has finished instantiating. More information can be found at http://docs.ckeditor.com/#!/api/CKEDITOR.config and http://docs.ckeditor.com/#!/api/CKEDITOR.editor-event-contentDom

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM