6

How can i get current x & y position of my CURSOR within a text area using javascript. The event is a Keyup event, not a mouse event.

I am not looking for the current cursor position in terms of charecter but x , y coordinates.

Wind Chimez
  • 1,166
  • 1
  • 9
  • 19

2 Answers2

1

The only somewhat reliable method I can think of is this:

  1. Create a <span> offscreen (absolutely positioned way to the left)
  2. Give it the same font characteristics as the input element.
  3. Continuously populate it with the text from the input element but before the caret
  4. Use a javascript library to find the pixel width of the offscreen span
  5. Use that to determine where the caret is relative to the left side of the input element.

Give it a shot, I'd love to hear how it turns out.

Daniel Beardsley
  • 19,907
  • 21
  • 66
  • 79
  • @WindChimez I have same problem as yours. Have you resolved this one? I wish you did! It's been 3 years now since you've raised this question. – Ivo San Feb 18 '13 at 06:40
0

Give this a shot:

 $(document).ready(function(){
    $('textarea').bind('keyup', function(e){
      var $this = $(this);
      alert('X: ' + $this.data('mousepos').x + '\nY: ' + $this.data('mousepos').y);
    });

    $('textarea').bind('mousemove', function(e){
      $(e.target).data('mousepos', {x: e.pageX, y: e.pageY});
    });
 });​

workin example: http://jsbin.com/ibowa3/edit

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • Thanks for quickly turning around to take a look at my query. But, it seems that it is not the right one. In the example you gave in the link, if we keep typing inside the textarea (leaving the mouse untouched) you can see the x & y are not changing, though the cursor is shifting its position. We need to consider the mouse is absent at all in this scenario – Wind Chimez Jun 17 '10 at 06:33
  • infact i tried the code myself as well, and it won't help. ITs getting the x,y upon mouse move and later on keyup giving the same i think. – Wind Chimez Jun 17 '10 at 06:40
  • I did not unterstand you well enough then, sorry. I don't think you can do that unfortunatly. You **are** able to get the `caret position` but I wouldn't know how to get the relative/absolute screen x/y coordinates based on that. – jAndy Jun 17 '10 at 06:45
  • Yeah, that's my problem too. i am getting the carret position. if user is typing in a single line, by using carret positon, i can somehow approximate the x cordinate by calculating the charecter width. But if he enteres a new line, then caret position will not help to judge the correct x & y – Wind Chimez Jun 17 '10 at 06:50
  • well you **could** even calculate the height of a linebreak, but that doesn't sound very convincing at all. Even if another `font-face`, `font-family`, `fontSize` etc. come into play. – jAndy Jun 17 '10 at 07:19