Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create tooltip at cursor position in text area with jQuery

Tags:

jquery

I'm trying to create a tooltip above the input caret in a text area. This would be easy if I could get the x,y coordinates of the caret in the text area, however I've been searching for a little while and cannot figure out how to do that.

Say a user is typing in a text area and then presses some key (@ symbol for instance). I'm trying to show a little tooltip above the text area caret.

Any ideas?

like image 489
Marc Avatar asked Sep 29 '11 20:09

Marc


People also ask

How can get current cursor position in textbox using jQuery?

Answer: Use the jQuery event. pageX and event. pageY pageX and event. pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.

How do I find the cursor position in text area?

First, get the current position of cursor with the help of property named as selectionStart on textarea/inputbox. To insert the text at the given position we will use slice function to break the string into two parts and then we will append both parts to the text(text_to_insert) in front and end of the text.

How do I change the cursor position in textarea?

To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.


2 Answers

Hmmm I do not really see anything in jQuery events that will easily give you an x y coord for the caret.

However there are quite a few ways for detecting the caret position in a text field:

http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html

Is it possible to programmatically detect the caret position within a <input type=text> element?

Caret position in textarea, in characters from the start

Using this, you could try to estimate the pixel coordinates for the tool tip.

If you want it to be more exact use a monospaced font inside of your text fields.

//depending on size of font
var charWidth = 10;
//using any number of the above methods to get caret position
var caretPosition = getCaretPos('#myTextField');
var textFieldOffsetX = $('#myTextField').offset.left;
var toopTipPositionX = caretPosition * charWidth + textFieldOffsetX;

It is not exact and it is not going to be perfect, but it might be close enough.

like image 109
Tyler J. Hutchison Avatar answered Oct 12 '22 14:10

Tyler J. Hutchison


Why does the tooltip have to be at the caret? Why not position it above (or somewhere around) the textarea? Here is a demo of what I mean.

$('textarea').keyup(function(e) {
    switch (e.which) {
        // @ symbol
    case 50:
        makeTooltip(e, 'you typed in an at symbol');
        break;
    }
});
like image 32
Mottie Avatar answered Sep 17 '22 14:09

Mottie