I'm using a bit of javascript written by The Great and Powerful Oz Tim Down that inserts things at the caret. It works great, but how can I restrict the function to only operate within a div with a class name of "editor-text"?
Edit: It must also work within other elements (such as H1) that may be within the .editor-text div.
Edit2: Must also work on new lines. See http://jsfiddle.net/j5mv219L/
The Live Demo: http://jsfiddle.net/wfo7gcvh/
The Code:
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(),
node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
tag in there. You can't paste into it because it's reading the H1 as the parent, not the specified class: http://jsfiddle.net/kthornbloom/wfo7gcvh/4/
– kthornbloom Mar 27 '15 at 15:09's. Any clues as to why? Here's an example: http://jsfiddle.net/j5mv219L/ – kthornbloom Apr 02 '15 at 02:08