Class FocusTrap

java.lang.Object
com.oorian.html.accessibility.FocusTrap

public class FocusTrap extends Object
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
    Modifier and Type
    Field
    Description
    static final String
    ID for the script element to prevent duplicates.
  • Constructor Summary

    Constructors
    Constructor
    Description
    FocusTrap(Element container)
    Creates a focus trap for the specified container.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Activates the focus trap.
    void
    Deactivates the focus trap without returning focus.
    void
    deactivate(Element returnFocusTo)
    Deactivates the focus trap and optionally returns focus to an element.
    boolean
    Checks if the focus trap is currently active.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Field Details

  • Constructor Details

    • FocusTrap

      public FocusTrap(Element container)
      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

      public void deactivate(Element returnFocusTo)
      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.