Smit Patel Smit Patel - 6 months ago 12
jQuery Question

full website control with keyboard (no mouse)?

So I started creating a site (html, css, js..) and I want to design my site so it's possible for someone without a mouse (just a keyboard) can use it.

If I have a

div
or
li
element, how can I make it get focus with tab or down arrow on the keyboard?

Example:

<ul class="nav-ul">
<li>
<a href="" class="nav-link" id="link-home">1
<img src="assets/home.png">
</a>
</li>
<li>
<a href="" class="nav-link" id="link-home">2
<img src="assets/home.png">
</a>
</li>
<li>
<a href="" class="nav-link" id="link-home">3
<img src="assets/home.png">
</a>
</li>
<li>
<a href="" class="nav-link" id="link-home">4
<img src="assets/home.png">
</a>
</li>
<li>
<a href="" class="nav-link" id="link-home">5
<img src="assets/home.png">
</a>
</li>
<li>
<a href="" class="nav-link" id="link-home">6
<img src="assets/home.png">
</a>
</li>
<li>
<a href="" class="nav-link" id="link-home">7
<img src="assets/home.png">
</a>
</li>




Here, I want each
li
element to gain focus when down arrow is pressed on the keyboard.

EDIT:

tabindex
DOES NOT WORK! i tried it many different ways. I want to have the same effect as it does when I hover over it.

EDIT 2

So I will make my question for clear. I do NOT want to use tab but instead it will be a D-pad (left, right, top, and bottom arrows).

Thank you.

Answer

The easiest way to achive this is to use tabindex attribute.

<li>
    <a href="" class="nav-link" id="link-home" tabindex='7'>7
        <img src="assets/home.png">
    </a>
</li>

Check some examples here

EDIT Navigating with left and right arrow:

document.addEventListener("keydown", function (e) {
   var focused = document.activeElement || document.body,
       focusables= document.getElementsByClassName("focusable"),
       len = focusables.length,
       step = 0;
   focusables = Array.from(focusables).sort(function(a,b) {
       return parseInt(a.tabIndex) - parseInt(b.tabIndex);
   });
   if (e.keyCode === 39) {
       step = 1
   }
   if (e.keyCode === 37) {
       step = -1
   }

   if (focused.tabIndex <0 || focused.tabIndex === len - 1 && step === 1) 
       focusables[0].focus()
   else if (focused.tabIndex === 0 && step === -1) 
       focusables[len-1].focus()
   else
       focusables[focused.tabIndex+step].focus()
});

Anything you need to do is to make your elements like this:

<a href="" class="nav-link focusable" id="link-home" tabindex="0">1
    <img src="assets/home.png">
</a>

Adding class focusable and setting tabindex Working example