javascriptjqueryhtmlkeyboardtabbing

How to use a selector to tab through elements using arrow keys?


I am trying to navigate a series of elements with the arrow keys, which I can successfully do like so:

Javascript:

$('div').keydown(function(e) {
  if (e.keyCode==39) {
    $('div').next(this).focus();
  }
  if (e.keyCode==37) {
    $('div').prev(this).focus();
  }
});

HTML:

<div tabindex='0'>
a
</div>
<div tabindex='0'>
b
</div>
<div tabindex='0'>
c
</div>

But if I add an element in between two divs, like so:

<div tabindex='0'>
a
</div>
<span tabindex='0'>
wat
</span>
<div tabindex='0'>
b
</div>
<div tabindex='0'>
c
</div>

The arrow keys do not skip the span and remain stuck on the second and third divs. Please see my demo for my implementation: http://jsfiddle.net/obliviga/a0uz64xw/5/

I basically want the focus with the arrow keys only to remain on a selector of my choice, so that the span is skipped. I'm not sure how to do this. Thanks.


Solution

  • You need to use nextAll() and prevAll() along with :first pseudo class selector since prev() and next() only selects immediate adjacent sibling. Where :first is helping to get the nearest one from the collection.

    $('div').keydown(function(e) {
      if (e.keyCode==39) {
        $(this).nextAll('div:first').focus();
      }
      if (e.keyCode==37) {
        $(this).prev('div:first').focus();
      }
    });
    

    $('div').keydown(function(e) {
      if (e.keyCode == 39) {
        $(this).nextAll('div:first').focus();
      }
      if (e.keyCode == 37) {
        $(this).prevAll('div:first').focus();
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div tabindex='0'>
      a
    </div>
    <span tabindex="0">
    wat
    </span>
    <div tabindex='0'>
      b
    </div>
    <div tabindex='0'>
      c
    </div>