Search code examples
ckeditor5writer

How do I focus the cursor at the end of inserted text in ckeditor5?


In the following code, the editor has some text inserted when a button is pressed, and then the editor focuses the cursor. However, it focuses the cursor at the beginning of the text area. I would like it to focus after the text that has been placed there. How is it possible? While I have looked at the API and using the writer, setSelection etc I don't understand them at all and have failed to use them correctly, so any help is appreciated.


<div id="editor">
  <p>Editor content goes here.</p>
</div>
<br>
<button id="focusSet">Focus</button>

<script>
  // 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>```
How would I change this code to set the cursor to the end of the text? This comes from a jsfiddle

[JsFiddle][1]


  [1]: https://jsfiddle.net/30mb2ef9/2/

Solution

  • The way I have done this is first set the text and then move the caret using createPositionAt.

    editorInstance.setData('TEXT TO SET');
    editorInstance.model.change( writer => {
        writer.setSelection( writer.createPositionAt( editorInstance.model.document.getRoot(), 'end' ));
    });