6

I'm making a file edit interface in my web-app, I have a textarea with file contents.

When textarea is focused, I want to output the position of the cursor, i.e. line number and column: this is useful because error messages usually yield a line number, for example.

The question is: how do I figure out the position of the cursor in textarea? I'm using prototype library. Maybe there's a solution already?

I'm not really interested in fancy toolbars for the textarea, which are offered by those advanced widgets.

Rob W
  • 328,606
  • 78
  • 779
  • 666
alamar
  • 18,172
  • 4
  • 63
  • 94

2 Answers2

11

When I want the current line number of textarea and current column of textarea, I solved like this:

<textarea  onkeyup="getLineNumberAndColumnIndex(this);" onmouseup="this.onkeyup();" >
</textarea>

function getLineNumberAndColumnIndex(textarea){
     var textLines = textarea.value.substr(0, textarea.selectionStart).split("\n");
     var currentLineNumber = textLines.length;
     var currentColumnIndex = textLines[textLines.length-1].length;
     console.log("Current Line Number "+ currentLineNumber+" Current Column Index "+currentColumnIndex );
  }
Aung Myat Hein
  • 3,788
  • 1
  • 34
  • 41
8

You may want to check out these 2 links:

http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/[The orginal source does not exist any more, the modified link points to the latest version of the Web Archive]

https://developer.mozilla.org/En/DOM:Selection

..once you have a selection (cursor index in text), you can split your text by newlines, thus getting line number. you can get column by determining index from beginning of a line

Rob W
  • 328,606
  • 78
  • 779
  • 666
skrat
  • 5,331
  • 3
  • 30
  • 46
  • 3
    FYI: The dedestruct.com link is dead as of April 11th, 2011. – drudge Apr 11 '11 at 21:49
  • Resolved broken link using the Web Archive: http://web.archive.org/web/20090221140237/http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/ – Rob W Dec 29 '11 at 15:42