Is there a way to have a textarea fire an event if the user changes which line the caret is on, say, by clicking or using the up/down arrows? Or is this just not possible in Javascript? I've found ways to find/set the current position of the caret, but that's not what I need...
Sounds like you need to register a couple events for your text area. off the top of my head, a click event, and a keypress event with multiple keycode values. Do you need to use pure javascript, or do you have some javascript libraries to utilize?
Do you need help registering events? or do you need help finding the caret position during one of the events? (see andy's link for that) or is the answer to both my questions "yes"?
ok, from you're comments you're ok with jquery, and the fieldselection plugin prevents you from re-inventing the wheel.
//jQuery 1.7
$(document).ready(function(){
var currentLine = -1;
$("#textAreaID").on("keypress", function(evt){
if(evt.which === 40 || ...){
//down arrow key, enter key, page down key, all will move the caret to a newline
$(this).trigger("newline");
}else{
//a ton of text in a fixed width textarea will move the cursor to a newline
$(this).trigger("checkForNewline");
}
}).on("click checkForNewline", function(evt){
var jqElem = $(this);
//fieldSelection plugin call
var range = jqElem.getSelection();
if(range["row"] && range["row"] !== currentLine){
currentLine = range["row"];
jqElem.trigger("newline");
}else{
var handTypedNewlines = jqElem.val().split(/\r\n|\r|\n/);
var userTypedRowcounts = Math.floor(wholeString.length / jqElem.cols) + (handTypedNewlines instanceof 'object')?handTypedNewlines.length:0;
if(userTypedRowcounts != currentLine){
currentLine = userTypedRowcounts;
jqElem.trigger("newline");
}
}
}).on("newline", function(evt){
// do your work, caret is on a newline.
});
});
referenced stack overflow.
reference to get .split() regex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With