Skip to content

Instantly share code, notes, and snippets.

@sergi
Created June 9, 2009 20:28
Show Gist options
  • Save sergi/126762 to your computer and use it in GitHub Desktop.
Save sergi/126762 to your computer and use it in GitHub Desktop.
Inserts node at selection (Gecko)
insertNodeAtSelection : function(win, insertNode, _container, _pos)
{
// get current selection
var sel = this._getSelection(); var doc = this._getDoc();
// get the first range of the selection (there's almost always only
// one range)
var range = sel.getRangeAt(0);
// deselect everything
sel.removeAllRanges();
// remove content of current selection from document
range.deleteContents();
// get location of current selection
var container = _container ? _container : range.startContainer; var
pos = _pos ? _pos : range.startOffset;
// make a new range for the new selection
range=doc.createRange();
if (container.nodeType==3 && insertNode.nodeType==3) {
// if we insert text in a textnode, do optimized insertion
container.insertData(pos, insertNode.nodeValue);
// put cursor after inserted text
range.setEnd(container, pos+insertNode.length);
range.setStart(container, pos+insertNode.length);
} else {
var afterNode;
if (container.nodeType==3) {
// when inserting into a textnode we create 2 new textnodes and
// put the insertNode in between
var textNode = container; container = textNode.parentNode; var
text = textNode.nodeValue;
// text before the split
var textBefore = text.substr(0,pos);
// text after the split
var textAfter = text.substr(pos);
var beforeNode = doc.createTextNode(textBefore); afterNode =
doc.createTextNode(textAfter);
// insert the 3 new nodes before the old one
container.insertBefore(afterNode, textNode);
container.insertBefore(insertNode, afterNode);
container.insertBefore(beforeNode, insertNode);
// remove the old node
container.removeChild(textNode);
} else {
// else simply insert the node
afterNode = container.childNodes[pos];
container.insertBefore(insertNode, afterNode);
}
range.setEnd(afterNode, 0); range.setStart(afterNode, 0);
}
sel.addRange(range); return {c:container, p:pos};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment