Ali Zia
Ali Zia

Reputation: 3875

How can I bind onchange and onkeyup with CKEDITOR?

I want to integrate a confirmation if we have unsaved form and user cancels, we show him a message. It is working perfectly for inputs but not for ckeditor. This is my code.

$(document).ready(function () {
    $('form').attr('onsubmit', 'disableBeforeUnload();');
    $('form input').attr('onchange', 'enableBeforeUnload();');
    $('form input').attr('onkeyup', 'enableBeforeUnload();');
    $('form textarea').attr('onchange', 'enableBeforeUnload();');
    $('form textarea').attr('onkeyup', 'enableBeforeUnload();');

});

function enableBeforeUnload() {
    window.onbeforeunload = function (e) {
        return "Discard changes?";
    };
}
function disableBeforeUnload() {
    window.onbeforeunload = null;
}

Any ideas how I can achieve this?

Upvotes: 0

Views: 567

Answers (1)

Wizard
Wizard

Reputation: 3151

There is a change event and a key event.

change event: Fired when the content of the editor is changed.

Due to performance reasons, it is not verified if the content really changed. The editor instead watches several editing actions that usually result in changes. This event may thus in some cases be fired when no changes happen or may even get fired twice.

If it is important not to get the change event fired too often, you should compare the previous and the current editor content inside the event listener. It is not recommended to do that on every change event.

Please note that the change event is only fired in the wysiwyg mode. In order to implement similar functionality in the source mode, you can listen for example to the key event or the native input event (not supported by Internet Explorer 8).

editor.on( 'mode', function() {
    if ( this.mode == 'source' ) {
        var editable = editor.editable();
        editable.attachListener( editable, 'input', function() {
            // Handle changes made in the source mode.
        } );
    }
} );

key event: Fired when any keyboard key (or a combination thereof) is pressed in the editing area.

editor.on( 'key', function( evt ) {
    if ( evt.data.keyCode == CKEDITOR.CTRL + 90 ) {
        // Do something...

        // Cancel the event, so other listeners will not be executed and
        // the keydown's default behavior will be prevented.
        evt.cancel();
    }
} );

Upvotes: 1

Related Questions