0

If I listen to the text box (textarea) key-down event, can I get the coordinates of event when user type any characters into it?

$('#textAreaId').bind('keydown', function(event) {    
    var data = event.originalEvent.touches ? event.originalEvent.touches[0] : event;
    alert(data.pageY);    
});
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
Darien Fawkes
  • 119
  • 1
  • 5
  • 16

2 Answers2

0

Do you want the position of the element or the position of the caret?

To get the position of the caret you can use the following function (borrowed from another question):

function getCaret(el) { 
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
        rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    return rc.text.length; 
  }  
  return 0; 
}

To get the position of the textarea element relative to the document, you use .offset:

$("#textAreaId").bind('keydown', function(event){
    var offset = $(this).offset();
    console.log(offset);
});

I put up a test case on jsFiddle.

Community
  • 1
  • 1
mekwall
  • 28,614
  • 6
  • 75
  • 77
  • Yes I olredy see code like this. But I try to get the exact coordinates of cursor in textArea from the top of the window. That's would be perfect solution. – Darien Fawkes Apr 28 '11 at 09:13
  • @Darien, for the cursor or the caret? – mekwall Apr 28 '11 at 10:26
  • Need x/y coordinates of caret it textArea. – Darien Fawkes Apr 28 '11 at 14:17
  • @Darien, sadly it's not possible to do that with the `textarea` element. Here's a working solution involving an offscreen `span` element: http://stackoverflow.com/questions/3059254/current-x-y-coordinates-of-cursor-in-text-area-using-javascript – mekwall Apr 29 '11 at 12:46
0

Caret position in textarea, in characters from the start

Community
  • 1
  • 1
alexl
  • 6,841
  • 3
  • 24
  • 29