3

After setting text in the editor, I need to set the focus to the end of the text. How to do it? I can not understand

editor.setData('text');
editor.editing.view.focus(); // focus to set the beginning, but on the end

Example: https://jsfiddle.net/ogm5s6k7/1/

// Editor configuration.
ClassicEditor
  .create( document.querySelector( '#editor' ))
  .then( editor => {
  window.editor = editor;
})
  .catch( error => {
  console.error( error );
});

document.getElementById('focusSet').onclick = function(e) {
  window.editor.setData('text');
  window.editor.editing.view.focus();
};
<script src="https://cdn.ckeditor.com/ckeditor5/11.1.0/classic/ckeditor.js"></script>
<div id="editor">
  <p>Editor content goes here.</p>
</div>
<br>
<button id="focusSet">Focus</button>
Szymon Cofalik
  • 1,142
  • 8
  • 9
DarkRiDDeR
  • 33
  • 1
  • 4

1 Answers1

7

To set selection in CKE5, you need to do it in "change block" where you have an access to the writer:

editor.model.change( writer => {
    writer.setSelection( ... );
} );

There are a couple of ways to set selection, see docs: https://ckeditor.com/docs/ckeditor5/latest/api/module_engine_model_writer-Writer.html#function-setSelection

Basically, you need some reference when setting selection. For example, if you want to set it after a given model node, you need a reference to that node and then you can use it like this:

writer.setSelection( myNode, 'after' );

If you want to set it at the end of the content you can use the document root:

writer.setSelection( editor.model.document.getRoot(), 'end' );
Szymon Cofalik
  • 1,142
  • 8
  • 9
  • The last one is really useful when you want to set autofocus at the end of CKE5. Just change selection to the end, after that just call `editor.editing.view.focus();`. – hastrb Jun 02 '23 at 10:36