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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With