DEV Community

Cover image for Trap focus using javaScript
Shubham Prakash
Shubham Prakash

Posted on

Trap focus using javaScript

Liquid syntax error: Unknown tag 'endraw'

Top comments (3)

Collapse
 
pulsipherd profile image
Deneb Pulsipher • Edited

I love this, Shubham! You do a good job explaining what's going on, step-by-step, and have moved me towards understanding how to do what I'm trying to do. Thank you! I wonder if you can help me close the gap, though, and get the rest of the way. I've been trying to use your code to make the navigation menu on a site (ideally any site by just modifying the querySelectorAll for the menu) navigable with the left and right arrows. That way menus with long drop-downs could be much more useful when navigating by keyboard than having to tab all the way through them. By targeting the querySelectorAll to the elements in my navigation menu, and changing the keyCodes to 37 and 39 I can navigate the menu fine with left and right arrows, but no matter where my focus is on the page, if I type left or right it jumps me to the menu, presumably because the eventListener is on the document. I tried moving the variables out of the function, and it still works fine, but when I try to move the handleInputFocusTransfer into a conditional statement based on one of the items in the menu array being the activeElement, it doesn't work. Here's what I've got that doesn't work:

const focusableMenuElements= document.querySelectorAll(#menu-sms-main-menu>li>a);
const focusable= [...focusableMenuElements];
if (focusable[0] === document.activeElement) {
document.addEventListener('keydown',handleMenuFocusTransfer);
}
function handleMenuFocusTransfer(e){
const index = focusable.indexOf(document.activeElement);
let nextIndex = 0;
if (e.keyCode === 37) {
// left arrow
e.preventDefault();
nextIndex= index > 0 ? index-1 : 0;
focusableMenuElements[nextIndex].focus();
}
else if (e.keyCode === 39) {
// right arrow
e.preventDefault();
nextIndex= index+1 < focusable.length ? index+1 : index;
focusableMenuElements[nextIndex].focus();
}
}

I'm a noob at JS, so it could be any number of little things making it wrong, but I'd sure appreciate your help!

Collapse
 
taufik_nurrohman profile image
Taufik Nurrohman
Collapse
 
ishubhamprakash profile image
Shubham Prakash

Nice article. Thanks for sharing 😄