How to determine if cursor position is on start of a defined row in textarea with JavaScript?
Asked
Active
Viewed 830 times
0
-
Possible duplicate: http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea – Gert Grenander Jul 03 '10 at 16:48
-
Nope ;) He wants to get cursor position in textarea ,I - to determine if the cursor is on start on defined row (e.g 3) – Jul 03 '10 at 16:54
2 Answers
0
Using the answer provided here:
Caret position in textarea, in characters from the start
you can get the offset of the cursor position in the text. After you have that, you can count the newline characters present in the text of the <textarea>
before the offset to figure out which line you are on. If the offset is just after a newline, then you're at the start of the row. Using these two methods, you should be able to figure out if you are at the start of a specific line. For example:
var offset = getCaret('mytextarea');
var text = document.getElementById('mytextarea').value;
var line_number = 1;
var i;
for ( i = 0; i < offset; i++ ) {
if ( text[i] == '\n' ) {
line_number++;
}
}
if ( !i || text[i-1] == '\n' ) {
// You're at the start of a line
}
Note: IE might use carriage returns (\r) as well, so you may have to account for them.
-
I have code ,which determines on which row(line) is the cursor ,but how to check if it's on the start of this row? – Jul 03 '10 at 17:06
-
If there's 'soft-wrap' this won't work for long lines that were wrapped. (I'm looking for a good solution to this issue but no luck so far.) – Jakub P. May 17 '12 at 00:00
-1
You could use one or a combination of the on events: onchange
, onkeyup
, onkeydown
, onkeypress
.
Provide a little more detail on your overall goal.

Jason McCreary
- 71,546
- 23
- 135
- 174
-
`onchange` will only fire when an input control loses focus *and* its value has been modified since gaining focus. http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-onchange – Marcel Korpel Jul 03 '10 at 16:48
-
Without additional specification in the OP, I was providing options. Who knows what on events may be helpful. – Jason McCreary Jul 03 '10 at 16:55
-
-
– As `onchange` will not fire when a field is not changed, the user can simply move the cursor to the beginning of a row of a `textarea` without this JavaScript event being fired. Though the OP is not very clear in his goal(s), it is understandable that that's not the intended behaviour. Not my down vote, BTW. – Marcel Korpel Jul 05 '10 at 16:08