Code Comments
Programming Forum and web based access to our favorite programming groups.How can you get the current position of the blinking cursor in a text
box or text area? How can you set this position programmatically?
Since I am impatient and didn't quickly find an answer, I decided to
make one up, and in a year, when I've forgotten I've done this already,
hopefully I'll find this post!
First, as far as I know, this can only be done in Microsoft Internet
Explorer. If anyone has methods they use for other browsers, please
feel free to add to this post.
Getting the cursor position is a bit convoluted because Microsoft
decided not to add some obvious properties to its TextRange object,
like the current position of the cursor! Luckily, with some stupid
TextRange tricks, we can determine it using a couple of TextRanges and
the compareEndPoints method (which is a little silly itself.) Copy and
paste the code below into a new HTML document and you can try it out
for yourself.
<script language="javascript">
// These functions ONLY work on MSIE (Win)
// Gets Cursor Position by comparing to a moving text range.
function GetCursorPosition() {
var obj = document.activeElement;
var cur = document.selection.createRange();
var pos = 0;
if (obj && cur) {
var tr = obj.createTextRange();
if (tr) {
while (cur.compareEndPoints("StartToStart", tr) > 0) {
tr.moveStart("character", 1);
pos++;
}
return pos;
}
}
return -1;
}
// Sets Cursor Position by creating a new text range and moving it
function SetCursorPosition(pos) {
var obj = document.activeElement;
if (obj) {
var tr = obj.createTextRange();
if (obj && tr) {
tr.moveStart("character", pos);
tr.collapse();
tr.select();
return true;
}
}
return false;
}
function ShowPos() {
var p = document.getElementById("pos");
p.value = GetCursorPosition();
}
function SetPos() {
var p = document.getElementById("pos");
var o = document.getElementById("bob");
o.focus();
SetCursorPosition(p.value);
ShowPos();
}
</script>
Cursor Position:
<input id="pos" size="3" value="n/a">
<input type="button" value="Set" onclick="SetPos();"><br>
<input id="bob" onclick="ShowPos();" onkeyup="ShowPos();" value="Click
in here">
Post Follow-up to this messageShadow Lynx wrote:
> How can you get the current position of the blinking cursor in a text
> box or text area? How can you set this position programmatically?
The following scrips might be helpfull. They are not fully tested, but
should give you an idea. They should work in both IE and Mozilla based
browsers.
function selectText(elm) {
elm.select();
}
function getSelectedText(elm) {
// this one is used especially for a XUL environment
if (!elm && document.commandDispatcher &&
document.commandDispatcher.focusedElement) {
elm = document.commandDispatcher.focusedElement;
}
if (elm && elm.setSelectionRange)
return elm.value.substring(elm.selectionStart, elm.selectionEnd);
else if (document.selection)
return document.selection.createRange().text;
}
function setSelectedTextRange(elm, selectionStart, selectionEnd) {
if (elm.setSelectionRange) {
elm.focus();
elm.setSelectionRange(selectionStart, selectionEnd);
}
else if (elm.createTextRange) {
var range = elm.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}
function setCaretToEnd (elm) {
setSelectedTextRange(elm, elm.value.length, elm.value.length);
}
function setCaretToStart (elm) {
setSelectedTextRange(elm, 0, 0);
}
function setCaretToPos (elm, pos) {
setSelectedTextRange(elm, pos, pos);
}
function getCaretPosition(elm) {
if (typeof elm.selectionStart != "undefined")
return elm.selectionStart;
else if (document.selection)
return
Math.abs(document.selection.createRange().moveStart("character",-1000000));
}
function selectString (elm, string) {
var match = new RegExp(string, "i").exec(elm.value);
if (match) {
setSelectedTextRange (elm, match.index, match.index + match[0].length);
}
}
function replaceSelectedText (elm, replaceString) {
var isInput = isInList(elm.nodeName.toLowerCase(),"input,textarea");
if (isInput && elm.setSelectionRange) {
var selectionStart = elm.selectionStart;
var selectionEnd = elm.selectionEnd;
elm.value = elm.value.substring(0, selectionStart) + replaceString
+ elm.value.substring(selectionEnd);
if (selectionStart != selectionEnd) // has there been a selection
setSelectedTextRange(elm, selectionStart, selectionStart +
replaceString.length);
else // set caret
setCaretToPos(elm, selectionStart + replaceString.length);
}
// else if (!isInput && elm.ownerDocument) {
// elm.ownerDocument.defaultView.getSelection().deleteFromDocument() {
// }
else if (document.selection) {
var range = document.selection.createRange();
if (range.parentElement() == elm) {
var isCollapsed = range.text == '';
range.text = replaceString;
if (!isCollapsed) { // there has been a selection
//it appears range.select() should select the newly
//inserted text but that fails with IE
range.moveStart('character', -replaceString.length);
range.select();
}
}
}
}
Post Follow-up to this messageVery nice, Daniel. I wasn't paying attention to the MoveStart() method close enough - my while loop is totally unnecessary. Thanks for themethods including the non-IE support.
Post Follow-up to this messagePowered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.