Clashing functions causing issues

I have 2 functions applied to a flyout menu. The way the menu behaves is as such (I will be speaking about keyboard functionality specifically here).

There’s a button on the page which, when you hit “enter”, it will open the flyout menu and focus on the first focusable element in the flyout menu. One of the functions (let’s call it “A”) loops you through the menu and when you get to the end of the flyout, it will loop you to the beginning of the flyout. The logic is that it’s a sort of way to keep the focus in the flyout until the user purposefully closes the menu. This function is called on the parent flyout div on keydown.

Inside of the flyout, I have a complex function (B) running. Don’t ask me why it’s doing this, but I am controlling the focus order via tabindex. In the screencast below, it’s what allows me to tab onto submenus, but as you can see in the screencast, it’s broken.

What’s happening is this. Let’s imagine I’m on the Giving → New Page2 link. I hit tab. The function “B” will actually move the focus onto the last menu item (Giving → New Page3) which then triggers function A (because it detected a tab + as far as function A is concerned, we are on the last focusable element in the flyout) and moves it to the “close button” in the screencast.

Both functions work great independently - the looping function and the menu accessibility, but together, they create problems. There’s a lot of code so I’m trying to avoid posting too much of it. Anyone have ideas? Let me know if I need to give more information.