tags:

views:

36

answers:

2

How to determine if cursor position is on start of a defined row in textarea with JavaScript?

A: 

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
`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
Without additional specification in the OP, I was providing options. Who knows what on events may be helpful.
Jason McCreary
OK ,I could use onkeydown ,but how to do the check?
lam3r4370
@Jason – 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
+1  A: 

Using the answer provided here:

http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea

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.

tomit
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?
lam3r4370
Updated my answer
tomit