Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the cursor location (X/Y, not line/column) in an HTML textarea? [duplicate]

Tags:

I'd like to display a dropdown list in a <textarea> to assist the user in typing certain things. You know this from current IDEs as code completion. As you start typing something, a popup will appear right a the current cursor/caret location and you can navigate it using arrow keys to complete your text input.

I know how to get the cursor position in the text string (i.e. the character index of the cursor position) but I do not know how to get the X/Y coordinates (something like offsetWidth and offsetHeight) of the cursor inside the <textarea> element so that I can position my list element there. Is that possible in HTML/JavaScript, and how would it work?

like image 932
ygoe Avatar asked Aug 05 '11 07:08

ygoe


1 Answers

With an editable html input (in an iframe like CKeditor or Rich Text Editor or even better: jsfiddle) you could insert an empty span element at the caret position and get the position of that element to display your dropdown.

It might seem complex but I can't think of any other way to do this.

It has some extra possibilities when used for a code editor, you could color-code the text and format code like jsfiddle does, and maybe even build some kind of code-auto-complete for keywords etc.

like image 136
Willem Avatar answered Sep 27 '22 22:09

Willem