Skip to content

Instantly share code, notes, and snippets.

@mathisonian
Created November 13, 2012 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathisonian/4067528 to your computer and use it in GitHub Desktop.
Save mathisonian/4067528 to your computer and use it in GitHub Desktop.
Getting the starting index of selected text
/*
* 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;
}
@gfmclean
Copy link

gfmclean commented Nov 6, 2018

This is assuming that the text selected is unique withing the container.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment