CKEditor is the outstanding WYSIWYG editor we use on the Mozilla Developer Network.  We have many custom plugins and we do everything we can to make writing easy for contributors.  One trick I just picked up was skipping to an element within the editor by ID and setting the cursor focus within that element.  Here’s how!

The JavaScript

You’ll start by scrolling the element into view within CKEditor:

var element = editor.document.getById('someHeading');
var range;

if(element) {
    element.scrollIntoView();

    // Thank you S/O
    // http://stackoverflow.com/questions/16835365/set-cursor-to-specific-position-in-ckeditor
    range = editor.createRange();
    range.moveToPosition(element, CKEDITOR.POSITION_AFTER_START);
    editor.getSelection().selectRanges([range]);
}

With the element in view, you’ll attempt to insert the cursor at the beginning of the element using a Range.

Firefox will actually insert the cursor for you but Chrome wont, so the Range step is necessary.

Source: David Walsh

Leave a Reply