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
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

Incredible Demos

  • By
    Link Nudging with CSS3 Animations

    One of the more popular and simple effects I've featured on this blog over the past year has been linking nudging.  I've created this effect with three flavors of JavaScript:  MooTools, jQuery, and even the Dojo Toolkit.  Luckily CSS3 (almost) allows us to ditch...

  • By
    HTML5 Datalist

    One of the most used JavaScript widgets over the past decade has been the text box autocomplete widget.  Every JavaScript framework has their own autocomplete widget and many of them have become quite advanced.  Much like the placeholder attribute's introduction to markup, a frequently used...

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!