0

I am not sure if the | is called a keyboard cursor. Anyways I have an input control and I will like to get the coordinates of where the | is.

In other words if my input tag gas the text:

hello world | bla bla

then I will like to get the coordinates of the keyboard cursor. by taking a guess that looks like 80px towards the right and 5px towards the bottom.

I know how to get the position of the cursor and then I can estimate the location by counting the number of characters but that is not reliable because some letters are wider than others. In other words I will be able to tell that the cursor is at position 12 by using this technique.

Community
  • 1
  • 1
Tono Nam
  • 34,064
  • 78
  • 298
  • 470

2 Answers2

1

You can only have an exact value if you are using monospace fonts, and then multiplying the number of visible characters by the font width currently being used.

Milad Naseri
  • 4,053
  • 1
  • 27
  • 39
0

You can create another element (or another container with display:inline) with the same content as the text to the left from the cursor (text.value.substr(0,text.getCaretPosition()). After the #fakeText element add another one . Then make sure that all CSS styles for #fakeText are same as for your text-input/text-area, except for the display:inline.

Finally measure the position of #fakeCaret relatively to the top left corner of #fakeText. This method is the only one I know, which provides both x and y coordinates for variable-width fonts.

We use this approach at nk.pl to position autocompleter just below the caret.

qbolec
  • 5,374
  • 2
  • 35
  • 44