ngduc
ngduc

Reputation: 1413

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 ?

Upvotes: 7

Views: 5003

Answers (1)

dandavis
dandavis

Reputation: 16726

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.

Upvotes: 6

Related Questions