I have a contenteditable div in the page, subscribeTextEditor
.
And a panel container many icons, enable to select icon and insert to contenteditable div.
below code is not the first version.
after i found the first version does not work in ie8, it been modified many times.
now, this version is closest to work find except insert position is incorrect.
the detail of my problem is showing in note of below code.
// below function from
// http://stackoverflow.com/questions/6690752/
// insert-html-at-caret-in-a-contenteditable-div
function insertTextAtCursor(html) {
// if don't set focus on contenteditable div,
// this function just work find at the first time.
// after first time, its not work anymore
// and totally not work in ie8
document.getElementById('subscribeTextEditor').focus();
// before call this method, everything work fine
// but the position of insert icon is incorrect
// the position is imprecise somehow
// sometimes at the first position of contenteditable div
// and somtimes at the next position of previous insert text
setCursor(subscribeTextEditor, lastCursor);
var sel, range;
var text = html;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
var firstNode = frag.firstChild;
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
lastCursor = range.endOffset;
}
} else if (document.selection && document.selection.createRange) {
// for IE8
sel = document.selection;
var originalRange = sel.createRange();
originalRange.collapse(true);
sel.createRange().pasteHTML(html);
}
}
// below function from
// http://stackoverflow.com/questions/2871081/
// jquery-setting-cursor-position-in-contenteditable-div
function setCursor(node, pos) {
var node = (typeof node == "string" || node instanceof String) ? document
.getElementById(node) : node;
if (!node) {
return false;
} else if (node.createTextRange) {
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
} else if (node.setSelectionRange) {
node.setSelectionRange(pos, pos);
return true;
}
return false;
}