Shift focus with arrow keys in JavaScript
<p>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.</p>

<p>This is what I got so far:</p>

<pre><code>$(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 &lt; arr.length; i++)
   {

      if ( (arr[i].offset().left &lt; offset.left)  // This doesn't work for some reason
        &amp;&amp; ((offset.left - arr[i].offset().left) &lt; 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
</code></pre>

<p>});</p>

<p>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. </p>

<p>I'm not able to get this code to work (it contains a error) and I'm not completly sure it will even work.</p>

<p>Thnx in advance</p>

<p>[EDIT]: I guess I was a little vague. I do not only want to go left and right, but also up and down.</p>
