0

I need to insert text into a contenteditable div and then have the cursor be at the end of the inserted text.

I got the solution below from here Insert text at cursor in a content editable div.

That works great if the text is added to am empty div. But it does not work if the user has already typed in text. Or, if the function is used to insert text, the user then places the cursor somewhere inside the newly inside text, and the function is then called again. Then the cursor is left at the beginning of the inserted text.

EDIT: The code below works in IE, properly setting the cursor, but has the problem in Chrome.

function insertTextAtCursor(text) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode( document.createTextNode(text) );
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = text;
    }
}
Community
  • 1
  • 1
user984003
  • 28,050
  • 64
  • 189
  • 285
  • I have a jsfiddle here http://jsfiddle.net/JCc4W/ enlighten me by giving an example with an empty div and non-empty div scenarios. Thanks. – Edper May 17 '13 at 08:33

1 Answers1

1

Alright, once I realized it was a Chrome/IE thing I managed to find the answer tucked away inside one of the comments to the answer that I first found.

function insertTextAtCursor(text) { 
    var sel, range, html; 
    sel = window.getSelection();
    range = sel.getRangeAt(0); 
    range.deleteContents(); 
    var textNode = document.createTextNode(text);
    range.insertNode(textNode);
    range.setStartAfter(textNode);
    sel.removeAllRanges();
    sel.addRange(range);        
}
user984003
  • 28,050
  • 64
  • 189
  • 285