6

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();
    }
  }
});
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Grad van Horck
  • 4,488
  • 1
  • 21
  • 22

1 Answers1

5

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
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • Great... It worked :) (Forgot about this feature, and we decided to leave this feature out...) – Grad van Horck Jan 02 '12 at 11:19
  • I was ready to give up as well, but my boss really really really wanted it :P – Kees C. Bakker Jan 02 '12 at 11:21
  • @KeesC.Bakker hoping you can help me... I am initiating ckeditor via the following at the bottom of my page: window.onload = function() { CKEDITOR.replace('Message'); }; So where exactly do I put the code you have above to make this work? I have the following within my html: And the $Message is the following:

    – Abela Feb 27 '14 at 14:01