Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  16] [ 4]  / answers: 1 / hits: 46941  / 16 Years ago, thu, march 12, 2009, 12:00:00

I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked.



Is this possible?


More From » jquery

 Answers
90

By “the last position”, do you mean the end of the text?



Changing the ‘.value’ of a form field will move the cursor to the end in every browser except IE. With IE you have to get your hands dirty and deliberately manipulate the selection, using non-standard interfaces:



    if (browserIsIE) {
var range= element.createTextRange();
range.collapse(false);
range.select();
} else {
element.focus();
var v= element.value();
element.value= '';
element.value= v;
}


Or do you mean put the cursor back to the place it was previously, the last time the textarea was focused?



In every browser except IE, this will already happen just by calling ‘element.focus()’; the browser remembers the last cursor/selection position per input and puts it back on focus.



This would be quite tricky to reproduce in IE. You would have to poll all the time to check where the cursor/selection was, and remember that position if it was in an input element, then fetch the position for a given element when the button was pressed and restore it. This involves some really quite tedious manipulation of ‘document.selection.createRange()’.



I'm not aware of anything in jQuery that would help you do this, but there might be a plugin somewhere perhaps?


[#99861] Thursday, March 5, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zayne

Total Points: 366
Total Questions: 98
Total Answers: 98

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;