Tab Focus Trapping with textArea causes trap to leave container

4 weeks ago 26
ARTICLE AD BOX

I am doing focus trapping with the tab key and when i tab out of the textarea, the tabbing leaves the container. If I use an input instead then the focus trapping works... Any idea's on why focus trapping is not working with textarea?

const container = document.getElementById("SpecialInstructionsWindow"); const getFocusables = () => { return Array.from( container.querySelectorAll(`textarea:not([disabled]), button:not([disabled]`) ).sort((a, b) => (a.dataset.focusOrder ?? 9999) - (b.dataset.focusOrder ?? 9999) ); }; container.addEventListener("keydown", (e) => { if (e.key !== "Tab") return; const focusables = getFocusables(); if (focusables.length === 0) return; const first = focusables[0]; const last = focusables[focusables.length - 1]; // TAB (forward) if (!e.shiftKey && document.activeElement === last) { first.focus(); e.preventDefault(); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <div id="SpecialInstructionsWrapper"> <div id="SpecialInstructionsWindow"> <div id="SpecialInstructionsTitleBar" class="aw-bar-color"> <span id="SpecialInstructionsTitleSpan">Special Instructions</span> <div id="SpecialInstructionsCommandButtons"> <button id="btnSaveAndCloseSpecialInstructionsWindow" class="fa fa-save special-instructions" data-focus-order="2"></button> <button id="btnCloseSpecialInstructionsWindow" class="fa fa-close special-instructions" data-focus-order="3"></button> </div> </div> <div id="SpecialInstructionsTextAreaWrapper"> <textarea name="" id="txtSpecialInstructions" class="special-instructions" maxlength="1020" rows="5" data-focus-order="1"></textarea> </div> </div> </div>

Chris's user avatar

4

What debugging steps have you taken to resolve this? Have you verified that document.activeElement and last are the elements you expect them to be?

2025-12-30 18:34:41 +00:00

Commented 12 hours ago

@mykaf, the answer is yes, i debugged by stepping through the code and the first and last are correct

2025-12-30 19:07:11 +00:00

Commented 11 hours ago

When I run this code, last is the btnCloseSpecialInstructionsWindow button; is that your expectation? Because the active element when tabbing out of the textarea is the textarea and the conditional fails.

2025-12-30 19:12:37 +00:00

Commented 11 hours ago

@Yogi, maybe you can explain how its similar, because I'm talking about focus trapping, moving from one element to another using the tab key and staying within its container. My problem is tabbing out of the textarea to the next element in the list, not tabbing into it and not making indentations

2025-12-30 19:44:06 +00:00

Commented 11 hours ago

Read Entire Article