简体   繁体   中英

Go to first link in list with tab if button is clicked

I have a header and a toggable menu where I want the focus to go from the menu button to the first link in the menu, when the button is clicked. Because of the design/structure the menu button and the menu cannot be next to eachother. The menu consist of a list with a listitem of a link and a button. But I have some trouble to get it to work. What I basically want is the natural way of navigate to a menu with the tab key, even if the button and menu cannot be next to eachother.

This is my js:

const button = document.querySelector(".button");
const list = document.querySelector(".list");

button.addEventListener("click", this.setFocus.bind(this));

function setFocus(e) {
  if(list.classList.contains("show")) {
     if (e.keyCode == 9) {
        list.querySelector("a").focus();
     }
  }
}

And a fiddle

If you remove the if (e.keyCode == 9) check, your code will work as expected.

By default, in most browsers the focus effect won't display a visual effect on all elements unless it's applied by the keyboard, so in this example I have added a red background to highlight what's happening.

 const button = document.querySelector(".button"); const list = document.querySelector(".list"); button.addEventListener("click", this.setFocus.bind(this)); function setFocus(e) { if (list.classList.contains("show")) { list.querySelector("a").focus(); } }
 :focus { background: red; }
 <button class="button">Menu</button> <a href="#">Another link</a> <ul class="list show"> <li class="li"> <a class="link" href="#">Link</a> <button class="button">chevron</button> </li> <li class="li"> <a class="link" href="#">Link</a> <button class="button">chevron</button> </li> <li class="li"> <a class="link" href="#">Link</a> <button class="button">chevron</button> </li> </ul>

If you want a visual effect in this case, you could apply a style to .link:focus (Chrome uses something along the lines of outline: #000 1px; )

I think you are trying to tab through the links without focussing on the buttons? In which case, you can set the tabindex of the buttons to -1. This prevents them being in focus when tabbing through the elements.

<button class="button" tabindex="-1">chevron</button>

Also, you are mixing your events. The event is 'click' and you are checking for a tab press. Just get rid of that check to auto focus on the first element.

function setFocus(e) {
  if(list.classList.contains("show")) {
    list.querySelector("a").focus();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM