0

I'm about to embark in creating a Jquery plugin that will provide a type ahead lookup in a similar way to how it's presented in visual studio.

Whilst I'm familiar to autocomplete and other similar type ahead plugins I want to make it so that the pop up is positioned under the word that's being typed in a text area.

Is there a way to get the current x and y of the caret within a text box?

Thanks

Sam

rlemon
  • 17,518
  • 14
  • 92
  • 123
sambomartin
  • 6,663
  • 7
  • 40
  • 64
  • possible duplicate: http://stackoverflow.com/questions/5149683/how-to-get-selected-text-caret-position-of-an-input-that-doesnt-have-focus – therin Jul 19 '12 at 20:19
  • Thanks but I believe that's referring to the position of the caret within the character string, not screen position relative to window/element – sambomartin Jul 19 '12 at 20:21

2 Answers2

0

There is a complex solution which involves overlaying the input with a canvas element and measuring the text in that (or just having a hidden canvas element) - but this I don't think will work in older IE.

You can measure the width of the text by adding up the characters and their relative width (with a known width mono font). Then just grabbing the input's top/left and adding the charWidth * num of chars prior to the word (including whitespace) should give you an somewhat accurate 'top/left' of the end (or beginning if you make it this way) of the word.

If you need a coded example let me know and I can whip up something suitable. However this (imo) would be the easiest way to do this (mono font + calculating widths + input offsets)

rlemon
  • 17,518
  • 14
  • 92
  • 123
  • Curious...will this work in a textarea where the lines have wrapped? – Daniel Szabo Jul 19 '12 at 21:30
  • Possibly... you can read some of the docs on ranges and how to determine new lines.. or do like a lot of Wysiwyg and offer a iframe + off screen input or contenteditable div maybe? – rlemon Jul 20 '12 at 01:00
  • Thanks for suggestions, From what I can find out its not really possible. I've learnt a lot about range js helpers like rangy so that's been useful. Maybe best solution would be fixed height and width fonts. Thanks – sambomartin Jul 23 '12 at 19:56
0

You can achieve using selection and range API's. But there are lot of differences with API's between IE and Non-IE. Please look into msdn and mdn for selection and range API's.

tgvrs santhosh
  • 408
  • 2
  • 9