Restrict ''read next element'' to modal window while using arrow keys

36 Views Asked by At

I need to be able to loop through the text elements in my modal window using the arrow keys (up and down). I want to prevent the user from being able to access the text elements outside of said modal window with said keys. I know some people might say restricting the user is not good practice, but it's being used in a very specific context.

I am able to restrict 'tab' and 'shift + tab' to my modal by monitoring the element being focused currently and then refocusing the first (or last) focusable element in the modal, thus creating a 'loop'.

My problem here is that the arrow keys don't change the focused element, they simply navigate through the text elements (which I can see in my NVDA text reader). Thus, I can't simply rely on what element the focus is on. I would like to find a way know what is currently being read so that I implement a logic to create a similar 'loop' using javascript.

Here is an example of my code for 'tab' and 'shift + tab' (not the actual code):

Handler for shift and tab:

if (event.key === 'Tab') {
  focusThings('tab');
}
if (event.shiftKey === true && event.key === 'Tab') {
  focusThings('shiftTab');
}

Which then calls focusThings():

if (tab && last_focused_element) {
      firstFocusable.focus();
      event.preventDefault();
      return;
    }
if (shiftTab && first_focused_element) {
      (lastFocusable as HTMLElement).focus();
      event.preventDefault();
      return;
    }
0

There are 0 best solutions below