Set caret to end after focus CKEditor

Grad van Horck picture Grad van Horck · Oct 5, 2011 · Viewed 8.6k times · Source

Possible Duplicate:
CKEditor - Set cursor position to end of text

I have a <div> with a lot of content. After a click on this div, the CKEditor is loaded to edit this div.

Now I would like to set the caret/cursor to the end of the contents after replacing it with the editor.

My code currently is something like this:

var editor = CKEDITOR.replace('content', {
  // Settings

  // Event listeners
  on: {
    instanceReady: function(evt) {
      var editor = evt.editor;

      // give focus (displays caret at the beginning of the content, not the end)
      editor.focus();
    }
  }
});

Answer

Kees C. Bakker picture Kees C. Bakker · Jan 2, 2012

After a bit of fiddling, I've got it to work with the following code:

$(document).ready(function() {

    CKEDITOR.on('instanceReady', function(ev) {

        ev.editor.focus();

        var s = ev.editor.getSelection(); // getting selection
        var selected_ranges = s.getRanges(); // getting ranges
        var node = selected_ranges[0].startContainer; // selecting the starting node
        var parents = node.getParents(true);

        node = parents[parents.length - 2].getFirst();

        while (true) {
            var x = node.getNext();
            if (x == null) {
                break;
            }
            node = x;
        }

        s.selectElement(node);
        selected_ranges = s.getRanges();
        selected_ranges[0].collapse(false);  //  false collapses the range to the end of the selected node, true before the node.
        s.selectRanges(selected_ranges);  // putting the current selection there
    }

});

The idea is:

  1. Get the root node (not body)
  2. Advance to next node, until there are no more nodes to advance to.
  3. Select last node.
  4. Collapse it
  5. Set range