Code Comments

Programming Forum and web based access to our favorite programming groups.
For Programmers: Free Programming Magazines | New: Database administration forum
Registration is free! Edit your profileCalendarFind other membersFrequently Asked QuestionsSearch -> 
Post New Thread











Thread
Author

Get and Set the Cursor (Caret) Position in a TextBox or TextArea
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">


Report this thread to moderator Post Follow-up to this message
Old Post
Shadow Lynx
02-24-06 02:56 AM


Re: Get and Set the Cursor (Caret) Position in a TextBox or TextArea
Shadow 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();
}
}
}
}

Report this thread to moderator Post Follow-up to this message
Old Post
Daniel Kirsch
02-24-06 08:56 AM


Re: Get and Set the Cursor (Caret) Position in a TextBox or TextArea
Very nice, Daniel.  I wasn't paying attention to the MoveStart() method
close enough - my while loop is totally unnecessary.  Thanks for the
 methods including the non-IE support.


Report this thread to moderator Post Follow-up to this message
Old Post
Shadow Lynx
02-24-06 11:58 PM


Sponsored Links




Last Thread Next Thread Next
Search this forum -> 
Post New Thread

JScript archive

Show a Printable Version Send to friend Email This Page to Someone! subscribe to this thread Receive updates to this thread
Computer Consultants
Programming Jobs
Visual Basic Controls
SQL Server Programming
Webservices
Java Security
Visual Studio
C# Programming
Visual J++
Software engineering
Open source Software
Perl Programming
PHP Programming
ASP Programming
ASP .NET Programming
Visual Basic Programming
Windows Scripting Host
Java Programming
Java Help
Java Beans
VBScript
Cobol
MAC Applications
Unix Programming
Forum Jump:
All times are GMT. The time now is 11:08 AM.

 
Free MCSE Braindumps | Real Estate Topics

Programming forum archive

Copyrights CodeComments.com 2004 - 2006

Powered by vBulletin Copyright 2000-2006 Jelsoft Enterprises Limited.