Package com.oorian.html.accessibility
Class FocusTrap
java.lang.Object
com.oorian.html.accessibility.FocusTrap
Utility for trapping focus within a container element (for modals/dialogs).
Focus trapping is essential for modal dialogs and other overlay components to meet WCAG requirements. When a modal is open, keyboard users should not be able to tab outside the modal to interact with content behind it.
Features:
- Traps Tab and Shift+Tab within the container
- Automatically finds all focusable elements
- Wraps focus from last to first element and vice versa
- Optional return focus to trigger element on deactivation
Usage:
// Create a modal dialog
Div modal = new Div();
modal.setRole(AriaRole.DIALOG);
modal.setAriaModal(true);
modal.setId("my-modal");
// Create focus trap for the modal
FocusTrap focusTrap = new FocusTrap(modal);
// When showing the modal
Button openButton = new Button("Open Modal");
// ... on click handler:
focusTrap.activate();
// When closing the modal
focusTrap.deactivate(openButton); // Returns focus to open button
- Since:
- 2025
- Version:
- 1.0
- Author:
- Marvin P. Warble Jr.
- See Also:
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidactivate()Activates the focus trap.voidDeactivates the focus trap without returning focus.voiddeactivate(Element returnFocusTo) Deactivates the focus trap and optionally returns focus to an element.booleanisActive()Checks if the focus trap is currently active.
-
Field Details
-
SCRIPT_ID
ID for the script element to prevent duplicates.- See Also:
-
-
Constructor Details
-
FocusTrap
Creates a focus trap for the specified container.- Parameters:
container- The element to trap focus within.
-
-
Method Details
-
activate
public void activate()Activates the focus trap.Focus will be constrained to focusable elements within the container. The first focusable element will receive focus.
-
deactivate
Deactivates the focus trap and optionally returns focus to an element.- Parameters:
returnFocusTo- Element to return focus to (typically the trigger element).
-
deactivate
public void deactivate()Deactivates the focus trap without returning focus. -
isActive
public boolean isActive()Checks if the focus trap is currently active.- Returns:
- True if the focus trap is active.
-