3
votes

Is there a way to get text from contenteditable div from beginning to cursor position.
For example:

<div id="editableDiv" contenteditable="true">
    the quick brown fox jumps over a lazy dog.
</div>  

Assumption 1: cursor blinking after the word quick. The query to the function must return the quick

Assumption 2: cursor blinking at the end of the sentence. The query to the function must return the quick brown fox jumps over a lazy dog.

1
may be this could help you:---> stackoverflow.com/questions/17613431/…Jai

1 Answers

6
votes

Here is the solution

getTextFromHeadToCaret: function () {
            var element = document.getElementById("editableDiv");
            var caretOffset = 0;
            if (typeof window.getSelection != "undefined") {
                var range = window.getSelection().getRangeAt(0);
                var preCaretRange = range.cloneRange();
                preCaretRange.selectNodeContents(element);
                preCaretRange.setEnd(range.endContainer, range.endOffset);
                caretOffset = preCaretRange.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("EndToEnd", textRange);
                caretOffset = preCaretTextRange.text.length;
            }
            var divStr = $('#editableDiv').text();
            return divStr.substring(0, caretOffset);
        }