Return selectionStart for div?

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>
 
Y

Yann-Erwan Perio

I need to find a way to determine the character position of a users
selection in a div.

The following should demonstrate some methods you can use with ranges;
tested IE6 and Mozilla 1.7.


---
<div
onmouseup="alert(getCharPosition(this));"
onmousedown="prepare(this)">Hello, World</div>

<script type="text/javascript">
var getCharPosition=(function(){

function getSel(){
var sel=null;
if(
typeof document.selection!="undefined" &&
document.selection &&
document.selection.type=="Text"
){
sel=document.selection;
} else if(
window.getSelection &&
window.getSelection().rangeCount>0
){
sel=window.getSelection();
}
return sel;
}

function createRangeFromSel(sel){
var rng=null;
if(sel.createRange) {
rng=sel.createRange();
} else if(sel.getRangeAt) {
rng=sel.getRangeAt(0);
if(rng.toString()=="") rng=null;
}
return rng;
}

return function(el){
var sel=getSel(), rng, r2, i=-1;
if(sel){
rng=createRangeFromSel(sel);
if(rng){

if(rng.parentElement) {
if(rng.parentElement()==el){
r2=document.body.createTextRange();
r2.moveToElementText(el);
r2.collapse(true);
r2.setEndPoint("EndToStart", rng);
i=r2.text.length;
}
} else {
if(
rng.startContainer &&
rng.endContainer &&
rng.startContainer==rng.endContainer &&
rng.startContainer==rng.commonAncestorContainer &&
rng.commonAncestorContainer.parentNode==el
){

//make sure your DIV does not have any inner element,
//otherwise more code is required in order to filter
//text nodes and count chars

i=rng.startOffset;
}
}
}
}
return i;
};

})();

function prepare(el){
if(el.normalize) {
el.normalize();
}
}
</script>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,265
Messages
2,571,069
Members
48,771
Latest member
ElysaD

Latest Threads

Top