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?
source
share