WARNINGYou're reading the legacy documentation.
Sign up (with export icon)

(Legacy) API and events

Contribute to this guide Show the table of contents

CKEditor 5 API allows developers to interact with the editor and its plugins to create new behaviors. Through the event system, you can tailor reactions to specific actions that are happening.

Using the API

Copy link

The API allows you to do multiple things with the editor and its content:

editor.model.change( writer => {
    // Move selection to the end of the document.
    writer.setSelection(
        writer.createPositionAt( editor.model.document.getRoot(), 'end' )
    );

    // Execute the enter command.
    editor.execute( 'enter' );

    // Insert text.
    editor.model.change( writer => {
        editor.model.insertContent( writer.createText( 'The End!' ) );
    } );
} );
Copy code

In the example above, you use a selection and a command, and you change the content using the editor’s model. All of this could be reverted with one undo step. This is a simple example of what the API can do.

Check more examples how to use the API or deep dive into our step-by-step tutorial.

Using events

Copy link

The editor’s instance can also be used to set up listeners for events. Every plugin in the editor publishes events that you can subscribe to and interact with. For example, the Document#change:data event is fired when the document changes in such a way that is “visible” in the editor data:

editor.model.document.on( 'change:data', () => {
    console.log( 'The data has changed!' );
} );
Copy code

Events could be used to alter the behavior of the editor. Imagine a user wants to swap the Enter keystroke with the Shift + Enter combination, so Shift + Enter will insert a new block, while Enter will insert a <br>.

editor.editing.view.document.on( 'enter', ( evt, data ) => {
    data.preventDefault();
    evt.stop();

    if ( data.isSoft ) {
            editor.execute( 'enter' );
            editor.editing.view.scrollToTheSelection();

            return;
    }

    editor.execute( 'shiftEnter' );
    editor.editing.view.scrollToTheSelection();
}, { priority: 'high' } );
Copy code

You can find more information about events in the framework documentation.