ckeditorckeditor4.x

How could I go about disabling the enter key whilst inside th tags for ckeditor 4?


Whenever a user creates a table in ckeditor 4 and presses the enter key whilst inside a table header (th) it creates a new paragraph. A paragraph inside a th is invalid HTML. Ideally I'd like to disable the enter key whenever the cursor is inside a th.

I'm aware of the enterMode config (changing it to a br or a div instead of a paragraph when enter is pressed) but that doesn't really solve the problem.

I guess I need to hook into the keypress event and then check which element type is the parent of the element in which the cursor is residing? But I'm not sure how to do that.

There is a similar question here but I'm specifically looking to disable the enter key in a particular scenario not just entirely. ckeditor turn off enter key

Any help appreciated, thanks.


Solution

  • I've figured this out, seems to work as I desired:

    CKEDITOR.instances.editor1.on('key', function(event) {
        var enterKeyPressed = event.data.keyCode === 13;
    
        var isTH = CKEDITOR.instances.editor1.getSelection().getStartElement().$.nodeName === 'TH';
        var parentisTH = CKEDITOR.instances.editor1.getSelection().getStartElement().$.parentNode.nodeName === 'TH';
    
        if(enterKeyPressed && isTH || enterKeyPressed && parentisTH) {
            event.cancel();
        }
    
    });