I have an element like this:
<span contenteditable="">line 1 line 2 line 3 line 4 line 5 </span>
Let's say user's editing "line 4". How to get current line & line index (at the caret position) in that contenteditable element ?
here is a simple way to use selection properties and string splitting to count offsets:
<pre contenteditable="">line 1
line 2
line 3
line 4
line 5
</pre>
<button onclick=getPos()>show pos</button>
<script>
function getPos() {
var sel = document.getSelection(),
nd = sel.anchorNode,
text = nd.textContent.slice(0, sel.focusOffset);
var line=text.split("\n").length;
var col=text.split("\n").pop().length;
alert("row:"+line+", col:"+col )
}
</script>
obligatory fiddle: http://jsfiddle.net/9rvg81kw/
if you have many elements in your editable, you might need to replace nd.textContent
with elmWysiwygContainer.textContent
to get the lines of all the text instead of just the "current" node.
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