A web developer’s diary

April 11, 2007

Javascript: Positioning the cursor at the beginning of a textarea

Filed under: Javascript — Celia @ 7:13 am

I had been using the textarea.focus() function and saw that it behaves differently in different browsers. If there is no content in the textarea, all the browsers behave the same and they set the cursor position at the beginning of the textarea.

However, if there is some text contained in the textarea, IE positions the cursor at the end whereas safari positions the cursor at the beginning. After some frantic google searching, I found the below javascript would fix this discrepancy.

replybox=document.myform.reply;
replybox.focus(0);
if (replybox.setSelectionRange )
{
replybox.setSelectionRange(0,0);
}

This works fine in all the browsers. Let me know if this helped you.

Advertisements

1 Comment »

  1. My saviour šŸ™‚ Works like a charm.

    Comment by inomiad — December 9, 2007 @ 11:17 am | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: