Scroll to Element within CKEditor

By  on  

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.

Recent Features

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

Incredible Demos

  • By
    Printing MooTools Accordion Items

    Sometimes we're presented with unforeseen problems when it comes to our JavaScript effects. In this case, I'm talking about printing jQuery and MooTools accordions. Each "closed" accordion content element has its height set to 0 which means it will be hidden when the...

  • By
    Pure CSS Slide Up and Slide Down

    If I can avoid using JavaScript for element animations, I'm incredibly happy and driven to do so.  They're more efficient, don't require a JavaScript framework to manage steps, and they're more elegant.  One effect that is difficult to nail down with pure CSS is sliding up...

Discussion

  1. Instead of

    range.setStart(element, 0);
    range.setEnd(element, 0);
    

    you can simply use

    range.moveToPosition( element, CKEDITOR.POSITION_AFTER_START );
    
  2. Ahmad Raza Cheema

    This will work for sure.

    CKeditor.config.startupFocus = 'end';

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!