Created
August 8, 2014 01:44
-
-
Save chanakasan/4e20bb35d7a3f0ecedba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* insertTextAtCursor | |
* An Utility function | |
* @param href | |
* @param selectedText | |
*/ | |
function insertTextAtCursor(href, selectedText) { | |
var html = "<a href='" + href + "'>" + selectedText + "</a>"; | |
var selectPastedContent = false; | |
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 | |
// only relatively recently standardized and is not supported in | |
// some 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); | |
} | |
var firstNode = frag.firstChild; | |
range.insertNode(frag); | |
// Preserve the selection | |
if (lastNode) { | |
range = range.cloneRange(); | |
range.setStartAfter(lastNode); | |
if (selectPastedContent) { | |
range.setStartBefore(firstNode); | |
} else { | |
range.collapse(true); | |
} | |
sel.removeAllRanges(); | |
sel.addRange(range); | |
} | |
} | |
} else if ((sel = document.selection) && sel.type != "Control") { | |
// IE < 9 | |
var originalRange = sel.createRange(); | |
originalRange.collapse(true); | |
sel.createRange().pasteHTML(html); | |
if (selectPastedContent) { | |
range = sel.createRange(); | |
range.setEndPoint("StartToStart", originalRange); | |
range.select(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment