3

How can I position the caret in CKEditor3.x? I have 2 positions and I want use insertHTML() on both positions.

Pseudo-code:

editor.setCaret(20); // function does not exists
editor.insertHtml('::');
editor.setCaret(40); // function does not exists
editor.insertHtml('::');

I have tried (to set caret to position: 20):

var ranges = [];
var range = new CKEDITOR.dom.range( this.document );
range.startOffset = 20;
range.endOffset = 20;
ranges.push( range );
editor.getSelection().selectRanges( ranges );

This is not working. Can anybody help me please?

Ziad Akiki
  • 2,601
  • 2
  • 26
  • 41
user706420
  • 1,167
  • 3
  • 13
  • 23

2 Answers2

3

To insert text or do something with html in the editor you don't need to get the caret position.

Treat it as usual html.

P.S. If you probably want to restore cursor position after dom manipulating, try this

var s = editor.getSelection();
var selected_ranges = s.getRanges(); // save selected range
// do something
s.selectRanges(selected_ranges); // restore it
Boris S
  • 301
  • 3
  • 10
  • 2
    If you save a range before doing an insert and want the cursor to be positioned AFTER the inserted element, this doesn't work. It puts the cursor BEFORE the inserted element. Still haven't found how to put the cursor after the inserted element. Normal behavior is that the cursor is INSIDE the inserted element, which doesn't work for some use cases (mine!). – eon Jan 11 '12 at 18:55
  • I see there is a function called `getSelectedElement()` (see http://docs.ckeditor.com/#!/api/CKEDITOR.dom.selection-method-getSelectedElement) that should return an instance of `CKEDITOR.dom.element` which has the method `focusNext` (see http://docs.ckeditor.com/#!/api/CKEDITOR.dom.element-method-focusNext) which should move the focus to the next element. But I just can't get it work =/ maybe somebody could dig into that direction.. – s3v3n Jul 05 '13 at 14:17
2

If you use insertElement instead of insert html (and say, insert a span element) the following should probably work:

editor.insertElement(element);
var range = new CKEDITOR.dom.range(editor.document);
range.moveToElementEditablePosition(element, true);
editor.getSelection().selectRanges([range]);
Ron Shalit
  • 21
  • 1