JAVASCRIPT

Programmatic Focus Management for Enhanced Accessibility

Control keyboard focus programmatically using JavaScript to guide users, improve navigation, and enhance accessibility in web applications, especially for modals or forms.

function openModal() {
  document.getElementById('modal').style.display = 'block';
  // Set focus to the first interactive element inside the modal
  document.getElementById('modalInput').focus();
}

function closeModal() {
  document.getElementById('modal').style.display = 'none';
  // Return focus to the element that opened the modal, if desired
  // For simplicity, we'll focus a general button here
  document.getElementById('openModalBtn').focus();
}

document.getElementById('openModalBtn').addEventListener('click', openModal);
document.getElementById('closeModalBtn').addEventListener('click', closeModal);

// Trap focus within a modal (basic example)
document.getElementById('modal').addEventListener('keydown', function(event) {
  const focusableElements = this.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
  const firstElement = focusableElements[0];
  const lastElement = focusableElements[focusableElements.length - 1];

  if (event.key === 'Tab') {
    if (event.shiftKey) { // Shift + Tab
      if (document.activeElement === firstElement) {
        lastElement.focus();
        event.preventDefault();
      }
    } else { // Tab
      if (document.activeElement === lastElement) {
        firstElement.focus();
        event.preventDefault();
      }
    }
  }
});

/* HTML Structure Example:
<button id="openModalBtn">Open Modal</button>

<div id="modal" style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid black; padding: 20px; background: white; z-index: 1000;">
  <h2>Modal Title</h2>
  <input type="text" id="modalInput" placeholder="Enter something...">
  <button>Action Button</button>
  <button id="closeModalBtn">Close</button>
</div>
*/
How it works: Programmatic focus management is crucial for accessibility, especially when dealing with dynamic content like modals, dropdowns, or complex forms. By using `element.focus()` and `element.blur()`, developers can explicitly control which element receives keyboard focus. This ensures that screen reader users and keyboard navigators can easily interact with newly presented content or return to their previous position. The example also demonstrates a basic focus trap within a modal, preventing users from tabbing outside the modal content until it's closed, significantly improving the user experience for assistive technologies.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs