Determine if cursor is at the end of textarea with JavaScript
I had a textarea in a form that I wanted to submit on pressing the ‘Enter’ key. I have the code to do that:
http://jdev.blogsome.com/2007/03/12/capture-enter-key-on-form-submission/
But the problem is that if you use it on a textarea, a user can’t use the Enter key to insert a line break. The solution is to find the cursor’s position and submit the form only if the cursor is at the end of the text. After some digging on the Internet I came up with this code:
function isEndPosition (tArea){
var tval = rtrim(tArea.value);
//Firefox
if(tArea.selectionStart){
var selStart = tArea.value.substr(0, tArea.selectionStart);
return (selStart.length - tval.length >=0);
}
//IE
else {
tArea.focus();
len = caret(tArea);
return (len - tval.length >=0 || len == -1)
}
}
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
The function returns true if the cursor is at the end of the text. It accepts a textarea object as a parameter. Tested in Firefox and IE 6.
The ‘caret()’ function for IE is at http://www.csie.ntu.edu.tw/~b88039/html/jslib/caret.html
More JavaScript tips at http://www.ekcsoft.com/coding/js.php