azemi
azemi

Reputation: 381

Traverse through div elements using tab index

So, I'm creating a Memory Game and I want to be able to select and flip the different cards using the keyboard. Right now I'm using tab index on the cards (which are DIV elements), but the problem is that when traversing over the cards using TAB I'm not selecting the cards in the correct order, rather it's jumping around when selecting. I have tried setting the tab index value to different values, such as the first card having the lowest value and the last card having the highest value.

So, my question is: How can I traverse the cards with the tab key in the correct order?

Note, I'm only using vanilla javascript.

My Memeory Game

Upvotes: 0

Views: 743

Answers (1)

KooiInc
KooiInc

Reputation: 122936

Next time, try to provide a minimal reproducable example.

Here's one: sort the elements on their tabindex property value:

document.querySelector(`[tabindex="1"]`).focus();
const sortedDivsOnTabIndex = [...document.querySelectorAll(`[tabindex]`)]
  .sort((divA, divB) =>
    +divA.getAttribute(`tabindex`) - +divB.getAttribute(`tabindex`));

// result
document.querySelector(`pre`).textContent = sortedDivsOnTabIndex
  .map(div =>
    `tabindex ${div.getAttribute(`tabindex`)}, content "${div.textContent}"`)
  .join(`\n`);
#tiContainer {
  display: inline-block;
  width: 12rem;
}
pre {
  display: inline-block;
  position: absolute;
  top: 0;
  left: 13rem; 
  padding-left: 1rem;
  border-left: 1px solid #999;
}
<div id=tiContainer>
  <div tabindex=3>t3</div>
  <div tabindex=4>t4</div>
  <div tabindex=8>t8</div>
  <div tabindex=6>t6</div>
  <div tabindex=1>t1</div>
  <div tabindex=9>t9</div>
  <div tabindex=2>t2</div>
  <div tabindex=10>t10</div>
  <div tabindex=7>t7</div>
  <div tabindex=5>t5</div>
</div>
<pre></pre>

Upvotes: 2

Related Questions