I need to find a way to determine the character position of a users
selection in a div. I can do this with the following using an input
text box. Any way for a div or any text within the body tags?
<html>
<body>
<form>
<div onkeyup="s(this )" onclick="s(this )" id="myDiv">Thi s is some
text</div>
<input type="text" onkeyup="s(this )" onclick="s(this )" value="This is
some text">
</form>
<script type="text/javascript">
function s(el)
{
var sel, rng, r2, i=-1;
//firefox
if(typeof el.selectionSta rt=="number")
{
i=el.selectionS tart;
}
//ie
else if(document.sel ection && el.createTextRa nge)
{
sel=document.se lection;
if(sel)
{
r2=sel.createRa nge();
rng=el.createTe xtRange();
rng.setEndPoint ("EndToStart ", r2);
i=rng.text.leng th;
}
}
else
{
el.onkeyup=null ;
el.onclick=null ;
}
alert(i)
}
</script>
</body>
</html>