views:

70

answers:

2

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.

A: 

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
Wind Chimez
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
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
Wind Chimez
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
A: 

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
well,let me try out that.
Wind Chimez