1

I want to add content to the TinyMce editor automatically at a specific place. For this i use the following example:

First what you should do is add a span at the end of the content you want to create. Then once inserted, do this...

ed.selection.select(ed.dom.select('span#caret_pos_holder')[0]); //select the span ed.dom.remove(ed.dom.select('span#caret_pos_holder')[0]); //remove the span

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

This works fine in de Chrome but throws an error in IE

"DOM Exception: INDEX_SIZE_ERR (1)"

Community
  • 1
  • 1
Jeroen
  • 1,991
  • 2
  • 16
  • 32

1 Answers1

1

Here is the function (located in one of my own custom plugins) i use

    // sets the caret position
    // ed is the editor instance
    // element is the html element located in the editor
    // start defines if the caret should get set to the start of the element (otherwise the end)
    setCursor: function (ed, element, start) {

        var doc = ed.getDoc();
        var edwin = ed.getWin();
        if (typeof doc.createRange != "undefined") {
            var range = ed.selection.dom.createRng();
            range.selectNodeContents(element);
            range.collapse(start);
            var win = doc.defaultView || doc.parentWindow;
            var sel = tinymce.isIE ? doc.selection : edwin.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (typeof doc.body.createTextRange != "undefined") {
            var textRange = doc.body.createTextRange();
            textRange.moveToElementText(element);
            textRange.collapse(start);
            textRange.select();
        }
    },

Example call:

setCursor(ed, $(ed.getBody()).find('span#caret_pos_holder').get(0), 0);
Thariama
  • 50,002
  • 13
  • 138
  • 166