Created
November 13, 2012 18:34
-
-
Save mathisonian/4067528 to your computer and use it in GitHub Desktop.
Getting the starting index of selected text
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
/* | |
* Gets the starting index of the selected text | |
*/ | |
function _getSelectionHtml() { | |
/* | |
* Returns HTML String of current selection | |
*/ | |
var html = ""; | |
if (typeof window.getSelection != "undefined") { | |
var sel = window.getSelection(); | |
if (sel.rangeCount) { | |
var container = document.createElement("div"); | |
for (var i = 0, len = sel.rangeCount; i < len; ++i) { | |
container.appendChild(sel.getRangeAt(i).cloneContents()); | |
} | |
html = container.innerHTML; | |
} | |
} else if (typeof document.selection != "undefined") { | |
if (document.selection.type == "Text") { | |
html = document.selection.createRange().htmlText; | |
} | |
} | |
return html; | |
} | |
// Get all the html in your text container | |
var textContainerHtml = $('.myTextContainer').html(); | |
// Get the the html string that was selected using the above function | |
var selectedHtml = _getSelectionHtml(); | |
// Set the starting and ending index | |
var index = -1; | |
var endex = -1; | |
if (selectedHtml) { | |
index = textContainerHtml.indexOf(selectedHtml); | |
endex = index + selectedHtml.length; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is assuming that the text selected is unique withing the container.