D
Dean A. Hoover
I am quite new to javascript and am attempting
to write a function that will return the index
of the start of a selection, whether of not it
is "collapsed". I've got it working if its not
collapsed, and I've also got a getSelectionEnd
function working. I did this primarily by searching
the internet and finding similar stuff, so you
may recognize some of it. But I did not find
anything that specifically addresses this
problem. If this has been covered before, I
apologize as I have not seen it. My code
follows.
Thanks
Dean Hoover
function getSelectionStart(input)
{
if (input.setSelectionRange)
{
// Mozilla
return input.selectionStart;
}
else if (document.selection)
{
// IE
var textRange = document.selection.createRange().duplicate();
var pos;
if (textRange.text.length > 0)
{
// selection is not collapsed
pos = input.value.indexOf(textRange.text);
}
else
{
// selection is collapsed
pos = 0; // How do I compute this?
}
return pos;
}
else
{
return 0;
}
}
function getSelectionEnd(input)
{
if (input.setSelectionRange)
{
// Mozilla
return input.selectionEnd;
}
else if (document.selection)
{
// IE
var selectedRange = document.selection.createRange().duplicate();
selectedRange.moveStart("character", -input.value.length);
return selectedRange.text.length;
}
else
{
return 0;
}
}
to write a function that will return the index
of the start of a selection, whether of not it
is "collapsed". I've got it working if its not
collapsed, and I've also got a getSelectionEnd
function working. I did this primarily by searching
the internet and finding similar stuff, so you
may recognize some of it. But I did not find
anything that specifically addresses this
problem. If this has been covered before, I
apologize as I have not seen it. My code
follows.
Thanks
Dean Hoover
function getSelectionStart(input)
{
if (input.setSelectionRange)
{
// Mozilla
return input.selectionStart;
}
else if (document.selection)
{
// IE
var textRange = document.selection.createRange().duplicate();
var pos;
if (textRange.text.length > 0)
{
// selection is not collapsed
pos = input.value.indexOf(textRange.text);
}
else
{
// selection is collapsed
pos = 0; // How do I compute this?
}
return pos;
}
else
{
return 0;
}
}
function getSelectionEnd(input)
{
if (input.setSelectionRange)
{
// Mozilla
return input.selectionEnd;
}
else if (document.selection)
{
// IE
var selectedRange = document.selection.createRange().duplicate();
selectedRange.moveStart("character", -input.value.length);
return selectedRange.text.length;
}
else
{
return 0;
}
}