J
jen_designs
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">This 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.selectionStart=="number")
{
i=el.selectionStart;
}
//ie
else if(document.selection && el.createTextRange)
{
sel=document.selection;
if(sel)
{
r2=sel.createRange();
rng=el.createTextRange();
rng.setEndPoint("EndToStart", r2);
i=rng.text.length;
}
}
else
{
el.onkeyup=null;
el.onclick=null;
}
alert(i)
}
</script>
</body>
</html>
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">This 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.selectionStart=="number")
{
i=el.selectionStart;
}
//ie
else if(document.selection && el.createTextRange)
{
sel=document.selection;
if(sel)
{
r2=sel.createRange();
rng=el.createTextRange();
rng.setEndPoint("EndToStart", r2);
i=rng.text.length;
}
}
else
{
el.onkeyup=null;
el.onclick=null;
}
alert(i)
}
</script>
</body>
</html>