I want to be able to navigate through all the focusable elements on my webpage with the arrow key. So when the down-key is pressed the focus should shift to the focusable element beneath the current focussed element. You get the idea for the other arrow keys, when there is not a focusable element to shift to, the focus should remain the same.
This is what I got so far:
$(document).keydown(function(e){
if (e.keyCode == 37) { //left
var offset = $("*:focus").offset();
var allElements = $("#container").find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]');
var arr = jQuery.makeArray(allElements);
var topLeft = offset.left
var minus = topLeft;
var currentElement = $("*:focus");
for(var i = 0; i < arr.length; i++)
{
if ( (arr[i].offset().left < offset.left) // This doesn't work for some reason
&& ((offset.left - arr[i].offset().left) < minus))
{
currentElement = arr[i];
minus = offset.left - arr[i].offset().left;
topLeft = arr[i].offset().left;
}
currentElement.focus();
}
alert( "left pressed" );
return false;
}
// Other Keys
});
the idea was to get all the focus-able elements and than pick select the one that is suited for the arrow and shift focus.
I'm not able to get this code to work (it contains a error) and I'm not completly sure it will even work.
Thnx in advance
[EDIT]: I guess I was a little vague. I do not only want to go left and right, but also up and down.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…