Focus the First Available Form Control

Last updated: August 27, 2026.

Prefer autofocus for one known field. For dynamic forms, find the first visible, enabled control.

function focusFirstAvailableControl(root = document) {
  const selector = [
    "input:not([type='hidden']):not([disabled])",
    "select:not([disabled])",
    "textarea:not([disabled])",
    "button:not([disabled])"
  ].join(",");
  const control = [...root.querySelectorAll(selector)].find((element) =>
    element.getClientRects().length > 0 && element.tabIndex >= 0
  );
  control?.focus({ preventScroll: true });
}

document.addEventListener("DOMContentLoaded", () => focusFirstAvailableControl());

Unexpected focus changes can disorient keyboard and screen-reader users, so use this only when it clearly helps.

admin

admin

Leave a Reply

Your email address will not be published.