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
    39 Shirts – Leaving Mozilla

    In 2001 I had just graduated from a small town high school and headed off to a small town college. I found myself in the quaint computer lab where the substandard computers featured two browsers: Internet Explorer and Mozilla. It was this lab where I fell...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    MooTools PulseFade Plugin

    I was recently driven to create a MooTools plugin that would take an element and fade it to a min from a max for a given number of times. Here's the result of my Moo-foolery. The MooTools JavaScript Options of the class include: min: (defaults to .5) the...

  • By
    Chris Coyier’s Favorite CodePen Demos IV

    Did you know you can triple-heart things on CodePen? We’ve had that little not-so-hidden feature forever. You can click that little heart button on any Pen (or Project, Collection, or Post) on CodePen to show the creator a little love, but you can click it again...

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!