Welcome to WebmasterWorld Guest from 18.232.53.231

Forum Moderators: open

Message Too Old, No Replies

moving the cursor position inside textarea

     
10:17 am on Sep 19, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:May 3, 2011
posts:64
votes: 0


Hi there,

I was looking for a way to move the cursor position within a textarea by a given offset.
I have a button that inserts a timestamp and a \n at the beginning of the textarea (moving the rest of the text inside it a line lower), and am looking for a way to move the cursor behind the timestamp instead of behind the whole text so the user could start typing after inserting the timestamp right away instead of having to click or typing at the end of the text.
The timestamp length is constant so there is no need to find out where the desired position is I just haven't got a clue how to move the cursor there, looking for a javascript way to do this without jquery..
10:53 am on Sept 19, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:May 3, 2011
posts:64
votes: 0


i was looking at createTextRange and move, moveStart, moveEnd, but all these used with select, which selects the given range. I don't want to select the text, I want to set the cursor position after the selected range, I just couldn't find how to do this anywhere..
3:22 pm on Sept 19, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:May 3, 2011
posts:64
votes: 0


ok apologies i found the solution, by just setting the setSelectionRange method's 2 parameters (start and end position) to the same location/number, respectively for non IE browsers doin something like
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();

:-) communicating with myself..
4:51 pm on Sept 23, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
posts:7999
votes: 0


Those are methods for IE only (if memory serves me right, it often doesn't . . . ) For Moz browsers you'll need to use selectionStart, selectionEnd, etc.

var allText = theField.value;
// IE
if (document.selection) {
var selectedText = document.selection;
// etc.
}
// NN/FF/Moz compat
else if ((theField.selectionStart) || (theField.selectionStart == 0)) {
var startPos = theField.selectionStart;
var endPos = theField.selectionEnd;
// etc.
}
else {alert('dynamic selection is not supported by your browser'); }

It definitely would be easier using jQuery and caret [plugins.jquery.com] :-)