Reputation: 377
I need to determine if a user is on the first line, or last line, of text in a textarea.
The reason for this is that the client has requested that when a user presses the up arrow while on the top line of text in a textarea they are taken to the previous form field, or if on the last line of text and pressing the down arrow the user is taken to the following form field.
I have found a way to determine which row of text the cursor is on, but it only works if the rows of the textarea are defined. Most of the the textarea's on the page are using the jQuery TextAreaExpander plugin, so their rows are not set.
Upvotes: 3
Views: 1167
Reputation: 14777
The following combination of HTML and JavaScript works for me in Chrome:
HTML:
<input id="bta"><br><br>
<textarea id="ta" cols="10" rows="2"></textarea><br><br>
<input id="ata">
JavaScript (using jQuery):
$(function() {
var $ata = $('#ata'),
$bta = $('#bta'),
$ta = $('#ta');
$ta.bind('keyup', function(e) {
if (this.selectionStart === 0 && e.keyCode === 38) {
$bta.val('Going up!').focus();
$ata.val('');
} else if (this.selectionStart === this.value.length && e.keyCode === 40) {
$ata.val('Going down!').focus();
$bta.val('');
}
});
});
In this example I am relying on an HTML5 property: selectionStart. I do not know if this will work in older browsers.
Upvotes: 0
Reputation: 104770
If you can get the cursor position on keydown, find the indexOf the previous (up arrow) or next (down arrow) newline character. If -1, go to the previous or next field.
Upvotes: 1