Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current line & line index in this contenteditable element?

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 ?

like image 456
ngduc Avatar asked Mar 15 '15 23:03

ngduc


1 Answers

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.

like image 154
dandavis Avatar answered Sep 30 '22 04:09

dandavis