Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get cursor row and column in a content-editable div

Tags:

javascript

There are several recipes for finding the cursor position as the user types text in a content-editable div, but I can't get any of them to work. In fact, I get the most surprising results from the simplest code; if, in this following snippet, you add some text and then backspace to remove it, your startoffset actually increments! (I can imagine its splitting elements or something and the offset includes non-printable tags or something.)

I have a div that will have a fixed font but which I plan to add syntax highlighting to (its not something codemirror can just do; its more interactive prompt with editing anywhere in the script if that kind of makes sense why I am want to get the 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 know the row and column, and get the text for any row, in such a content-editable div?

like image 488
Will Avatar asked Mar 31 '12 20:03

Will


1 Answers

Upon changing the onkeypress to an onkeydown (so that backspace is captured) I see that the position display increments once when a backspace is entered.

Forgive me if I've got the wrong end of the stick, but I believe one solution is doing 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;
}
like image 133
Griffin Avatar answered Oct 25 '22 06:10

Griffin