Get selected range of text according to main div (containing all text)

My requirement is to get the start and end character index of the text selected by the user relative to the main div, lets say the "content" div. See sample code below. But when I select the "Rich" word in the web view. Its starting and ending character index matches where the "span" tag is, that is, 1 and 5, respectively. Whereas it should be 12 and 16 wrt "content" divs.

<html>
<body>
    <div id="content" contenteditable="true" style="font-family: Times New Roman; color: #fff; font-size: 18;">
          This is <span style="background-color: yellow;">out</span> Rich Text Editing View
    </div>
</body>

      

The JavaScript function m currently using is

function getHighlightedString()
{
    var text = document.getSelection();
    startIndex = text.anchorOffset;
    endIndex = text.focusOffset;
    selectedText = text.anchorNode.textContent.substr(startIndex, endIndex - text.anchorOffset);
}

      

Please help me.

+3


source to share


1 answer


Here's an answer adapted from that . The same caveats from this answer apply.

Demo: http://jsfiddle.net/62Bcf/1/



code:

function getSelectionCharacterOffsetsWithin(element) {
    var startOffset = 0, endOffset = 0;
    if (typeof window.getSelection != "undefined") {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.startContainer, range.startOffset);
        startOffset = preCaretRange.toString().length;
        endOffset = startOffset + range.toString().length;
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        var preCaretTextRange = document.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToStart", textRange);
        startOffset = preCaretTextRange.text.length;
        endOffset = startOffset + textRange.text.length;
    }
    return { start: startOffset, end: endOffset };
}

      

+7


source







All Articles