Find caret position in textarea in pixels [duplicate]

This “raw code” works at least in IE.

Using the code you can put your <TEXTAREA> where ever you want in page, and the <DIV id="db"> will follow it. Even despite of the scrolling position of the page. You can fix the position of <DIV> by changing the literal numbers at d.style...6-statements.

<body>
<div id="db" style="position:absolute;left:-20px;top:-20px;border:1px solid red;">V</div>
<br><br><br>
<form id="props">
<textarea id="ta" style="width:200px;height:100px;" onkeyup="moveDiv();"></textarea>
</form>

<script>
<!--
var b=document.body;
var d=document.getElementById('db');
var a=document.getElementById('ta');

function moveDiv(){
    var sel=document.selection;
    var targ=sel.createRange();
    d.style.top=a.offsetTop+a.clientTop-d.clientHeight-6;
    d.style.left=targ.offsetLeft+b.scrollLeft-6;
    return;
}
// -->
</script>
</body>

Positioning of the <DIV> is not quite exact, but gets better when using fixed-width font in <TEXTAREA>.

Leave a Comment