Link to home
Start Free TrialLog in
Avatar of ags00
ags00

asked on

Focus at end of textarea

In my window_onload function, I am setting the focus on a textarea in my form.  It will show text previously entered in the textarea.  However it puts the cursor at the beginning of the text.

Is there a way I can make the cursor start at the end of what has been typed in?

Here is the function I'm currently using: document.getElementById("comment").focus();
Avatar of HemanthaKumar
HemanthaKumar

The trick is to append a space so that the focus goes down to the end of the textarea...

eg:
document.getElementById("comment").focus();
document.getElementById("comment").value = document.getElementById("comment").value  + " ";


PS: You can extend this technique to read the last char of the textarea and append that char by stripping the last char !



~Hemanth
ASKER CERTIFIED SOLUTION
Avatar of HemanthaKumar
HemanthaKumar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Roonaan
I googled a while and found a function which you can use to put the cursor at the end:
<script language="JavaScript" type="text/JavaScript">
function MoveToEnd(Element){

if ( Element.createTextRange )
Element.createTextRange().text += "";
else if ( Element.insertionPoint )
Element.insertionPoint = Element.text.length;
}
</script>

You might want to try to use a function like:
<script type="text/javascript">
function focusById(elemid)
{
  elem = document.getElementById(elemid);
  if(elem)
  {
    elem.focus();
    MoveToEnd(elem);
    elem.focus();
  }
}

I tested it on IE6.028 using a simple html:
<body onload="focusById('mygoto');">
<form>
 <input id="mygoto" value="soup" />
</form>
</body>

And it worked fine; but i haven't tested it on other clients though.

good luck

-r-
One drawback is the cursor moves to the end.. but textarea doesn't scroll up. TO achieve that use doScroll method to scroll down the pages