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
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • 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
    Create Twitter-Style Dropdowns Using MooTools

    Twitter does some great stuff with JavaScript. What I really appreciate about what they do is that there aren't any epic JS functionalities -- they're all simple touches. One of those simple touches is the "Login" dropdown on their homepage. I've taken...

  • By
    CSS content and attr

    CSS is becoming more and more powerful but in the sense that it allows us to do the little things easily.  There have been larger features added like transitions, animations, and transforms, but one feature that goes under the radar is generated content.  You saw a...

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!