Modal dialogs and popovers often need to keep keyboard focus inside themselves while they are open.
In this question, implement createFocusTrap(container), a simplified version of the core behavior from focus-trap.
The returned trap should:
activate() is called.Tab from the last tabbable element back to the first.Shift+Tab from the first tabbable element back to the last.deactivate() is called.const modal = document.querySelector('#modal');const trap = createFocusTrap(modal);trap.activate();document.activeElement;// First tabbable element inside #modal.
trap.deactivate();// Later Tab presses should no longer be intercepted by the trap.
createFocusTrap(container)
container (HTMLElement): The container whose descendants should keep focus within the trap.Returns an object with the following methods:
trap.activate()Activates the trap and moves focus to the first tabbable descendant inside container.
trap.deactivate()Deactivates the trap and removes its keyboard listeners.
container is guaranteed to have at least one tabbable descendant.button, input, select, textarea, a[href], and elements with non-negative tabIndex.Escape, outside clicks, outside focus changes, or empty traps in this question.console.log() aparecerão aqui.