Set focus and carret position in textarea according to mouse position, as if user had clicked

Posted by JeanHuguesRobert on Stack Overflow See other posts from Stack Overflow or by JeanHuguesRobert
Published on 2010-05-13T22:20:55Z Indexed on 2010/05/13 22:24 UTC
Read the original article Hit count: 379

Filed under:
|
|
|
|

Once a page with a textarea is loaded, I want some textarea to have the focus immediatly if the mouse cursor is inside that textarea. This is the easy part because a onmousehover handler can set the focus.

Now, how to I also set the position of the caret? I would like the caret to be where it would be if the user had clicked using the mouse to set the focus/caret.

The basic use case is :

  1. User clicks on a link and waits (mouse barely moves)
  2. A page is delivered, it contains a big textarea only, full of text
  3. User types using keyboard
  4. Characters are inserted right below the mouse cursor

Today the user has to wait until the caret is visible (at the top left of the textarea) and then click to move the caret before typing.

Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about textarea