Question

How can I get content from CKEditor 5 on blur?

Answer and Explanation

To get content from CKEditor 5 on blur, you can use the editor's built-in event system. The 'blur' event is triggered when the editor loses focus. Here's how you can achieve this:

1. Initialize CKEditor 5:

- First, ensure you have properly initialized CKEditor 5 on your page. This typically involves selecting the DOM element where the editor should be rendered.

2. Attach a 'blur' Event Listener:

- After initializing the editor, you can attach an event listener to the 'blur' event. This listener will execute a function when the editor loses focus.

3. Retrieve the Editor's Data:

- Inside the event listener, use the editor.getData() method to retrieve the current content of the editor. This method returns the content as an HTML string.

4. Example Code:

ClassicEditor
  .create( document.querySelector( '#editor' ) )
  .then( editor => {
    editor.on( 'blur', () => {
      const editorData = editor.getData();
      console.log( 'Editor content on blur:', editorData );
      // You can now use the editorData variable as needed
    });
  })
  .catch( error => {
    console.error( 'There was an error initializing the editor', error );
  });

5. Explanation:

- The code initializes CKEditor 5 on the element with the ID #editor.

- The .then() method is used to handle the promise returned by ClassicEditor.create().

- Inside the .then() block, an event listener is attached to the 'blur' event using editor.on('blur', ...).

- When the editor loses focus, the callback function is executed, which retrieves the editor's content using editor.getData() and logs it to the console.

6. Handling Errors:

- The .catch() method is used to handle any errors that might occur during the initialization of the editor.

By implementing this approach, you can effectively capture the content of CKEditor 5 whenever it loses focus, allowing you to perform actions such as saving the content or updating other parts of your application.

More questions

Dashboard
Image ID
Talk to AI
AI Photos
Get App