Search code examples
javascriptjqueryhtmlcsstabindex

Editing the tab order of elements in a div without adding tabindex to every element


Let's say my webpage has 3 divs, with a bunch of links in them. Like so:

<div class="first">
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
</div>
<div class="second">
    <input id="link1" type="text"/>
    <input id="link2" type="text"/>
    <input id="link3" type="text"/>
    <input id="link4" type="text"/>
</div>
<div class="third">
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
    <input type="text"/>
</div>

I want to be able to tab through the links in the first div in order, tab through the links in the second div out of order (link 1, link 4, link 2, then link 3), and tab through the links in the third div in order.

I've explored adding tabindex to the links in the second div, in the order that I want it to be, but since the tabindex of all the links in the third div is 0 by default, the tab order goes: the links in the first div, the links in the third div, and then the links in the second div.

The solution I'm thinking of is to add the customized tabindex to the second div's links, and then a tabindex to each link in the third div (based on the offset). This solution seems bad.

I was curious to know if there's a clean way to be able to do this. Thank you!


Solution

  • I would get tabindex added to all inputs in one loop with additional condition for second div. Probably something like this:

    inputs.each(function(i) { 
      if (!$(this).parent().hasClass("second")) {
         $(this).attr('tabindex', i + 1); 
         numstart = i + 1;    
      } else {
        $(this).attr('tabindex', numstart + order[orderindex]); 
        ++orderindex;
      } 
    });
    

    this way you can get them all nicely ordered and have an easy way to set order for 2nd div

    https://jsfiddle.net/6nkn8bvj/