What's the best way to set cursor/caret position?

First what you should do is add a span at the end of the content you want to create.

var ed = tinyMCE.activeEditor;

//add an empty span with a unique id
var endId = tinymce.DOM.uniqueId();
ed.dom.add(ed.getBody(), 'span', {'id': endId}, '');

//select that span
var newNode = ed.dom.select('span#' + endId);
ed.selection.select(newNode[0]);

This is a strategy used by the TinyMCE developers themselves in writing Selection.js. Reading the underlying source can be massively helpful for this kind of problem.


After spending over 15 hours on this issue (dedication, I know), I found a partial solution that works in FF and Safari, but not in IE. For the moment, this is good enough for me although I might continue working on it in the future.

The solution: When inserting HTML at the current caret position, the best function to use is:

tinyMCE.activeEditor.selection.setContent(htmlcontent);

In Firefox and Safari, this function will insert the content at the current caret position within the iframe that WordPress uses as a TinyMCE editor. The issue with IE 7 and 8 is that the function seems to add the content to the top of the page, not the iframe (i.e. it completely misses the text editor). To address this issue, I added a conditional statement based on this code that will use this function instead for IE:

tinyMCE.activeEditor.execCommand("mceInsertRawHTML", false, htmlcontent);

The issue for this second function, however, is that the caret position is set to the beginning of the post area after it has been called (with no hope of recalling it based on the browser range, etc.). Somewhere near the end I discovered that this function works to restore the caret position at the end of the inserted content with the first function:

tinyMCE.activeEditor.focus();

In addition, it restores the caret position to the end of the inserted content without having to calculate the length of the inserted text. The downside is that it only works with the first insertion function which seems to cause problems in IE 7 and IE 8 (which might be more of a WordPress fault than TinyMCE).

A wordy answer, I know. Feel free to ask questions for clarification.


It is so simple to move the cursor to the end that I can't believe the awful kludges that have been posted elsewhere online to do this. Mr. Spocke's answer wasn't initially helpful but in the end the API docs provided me with the answer. "Select all content and then collapse the selection":

ed.selection.select(ed.getBody(), true); // ed is the editor instance

ed.selection.collapse(false);

I hope this helps someone else as this thread is one of the first to come up in Google.