Reputation: 4047
In html form we need to move up or down using arrow keys to shift focus in the fields. following code works fine for all input elements. but in case of textarea there could be multiple lines so, if we move up or down cursor moves up or down in the textarea itself.
Now, I'm not getting how to move up the focus, if the cursor reaches in the first line of the textarea while pressing up arrow OR move down the focus if the cursor reaches at the end or in the last line of the textarea while pressing down arrow key.
Here is my partial code:
var INPUT_SELECTOR = ':input:enabled:visible';
var inputs = $(INPUT_SELECTOR)
$("form").on("keypress", "input", function(event){
// i is current input
if(event.keyCode === 38){ //action == 'up'
inp = inputs[i > 0 ? parseInt(i) - 1 : inputs.length - 1];
}
if(event.keyCode === 40){ //action == 'down'
inp = inputs[i < inputs.length - 1 ? parseInt(i) + 1 : 0];
}
// focus on the input
moveFocusTo(inp);
});
Our requirement for the up and down arrow keys is same as tab
and shift+tab
behaviour. everything is done, we have just stuck at textarea.
Upvotes: 1
Views: 773
Reputation: 1033
Sounds like you need to use https://developer.mozilla.org/en-US/docs/Web/API/event.relatedTarget#1003983
event.relatedTarget
Then you can check to see during the event what element the user is focused on and act accordingly.
Upvotes: 1