I will not go into the encoding, since you already have the code, I will explain to you the logic of this.
If your page has the following elements,
element0 (tabindex 1) → element1 (tabindex 2) → element2 (tabindex 3)
To prevent focus, you basically create a loop.
When the tab key is pressed on element 0, it jumps to element 1, as usual.
But when the tab key is pressed on element2, you need to prevent the default behavior of the browser (by the .preventDefault () event). We go to the element with a higher tabindex and give focus to the element.
The same methods when shift + tab is pressed on element0, you need to prevent the default browser behavior (event.preventDefault ()) and manually select focus for element2.
Thus, you create a cycle in which the focus never goes outside.
source share