Get row and cursor column in content editable div

There are several recipes for finding the cursor position, as the user enters the text into the div's editable content, but I cannot get them to work. In fact, I get the most unexpected results from the simplest code; if in this next snippet you add text and then back to delete it, your initial value actually increases! (I can imagine its splitting elements or something similar, and the offset includes non-printable tags or something else.)

I have a div that will have a fixed font, but which I plan to add syntax highlighting (it may not be something that codemirror can do: its a more interactive prompt with editing anywhere in the script, if that makes sense, why I I want to get a position myself.)

<html>
<head>
<script type="text/javascript">
<!--
var ta = null;

function onKeypress(event) {
    var range = window.getSelection().getRangeAt(0);
    document.getElementById("msg").textContent = ""+range.startContainer+","+range.startOffset;
}

function init() {
    ta = document.getElementById("ta");
    ta.focus();
    ta.onkeypress = onKeypress;
}
//-->
</script>
<body onload="init();">
<noscript>
Sorry, you need javascript.  Not much to see here otherwise; move along.
</noscript>
<p id="msg"></p><hr/>
<div id="ta" contenteditable="true" style="width:100%; height:100%; font-family: courier;">
</div>
</body>
</html>

How can I find out the row and column and get the text for any row in such a content-editable div?

+5
source share
2 answers

After changing onkeypress to onkeydown (to capture the backspace), I see that the position display increases once when the backspace is entered.

Forgive me if I have the wrong end of the stick, but I believe that one of the solutions does the following:

var ta = null;
var range = null;

function onKeyDown(event) {
    if(event.which != 8 && event.which != 46) {
        range = window.getSelection().getRangeAt(0);
        document.getElementById("msg").textContent = ""+range.startContainer+","+range.startOffset;
    }
}

function onKeyUp(event) {
    range = window.getSelection().getRangeAt(0);
    document.getElementById("msg").textContent = ""+range.startContainer+","+range.startOffset;
}

function init() {
    ta = document.getElementById("ta");
    ta.focus();
    ta.onkeydown = onKeyDown;
    ta.onkeyup = onKeyUp;
}
+1
source

div?

<textbox>edit my content</textbox>

div, innerHTML

alert(document.getElementById('theIdOfMyDiv').innerHTML);

var currentContent = document.getElementById('theIdOfMyDiv').innerHTML;
currentContent = currentContent + 'add some content';
-1

All Articles