Input showPicker Feature Detection

Open a date input's browser picker on click, guarding TypeError for pickerless input types and keeping the call inside a user gesture.

TypescriptForm Validation

Code

typescriptsnippet
26 lines
// showPicker feature detection: typeof check first, then try/catch for
// inputs without a picker. It also throws NotAllowedError when the call is
// not inside a user gesture, so wire it to a click handler.
function openPicker(input: HTMLInputElement): boolean {
  if (typeof input.showPicker !== "function") return false;
  try {
    input.showPicker();
    return true;
  } catch (error) {
    if (error instanceof TypeError) return false; // no picker for this input type
    throw error;
  }
}

if (typeof document === "undefined") {
  console.log("showPicker needs a browser DOM");
} else {
  const input = document.querySelector<HTMLInputElement>("#meeting-date");
  const button = document.querySelector<HTMLButtonElement>("#pick-button");
  button?.addEventListener("click", () => {
    if (input && openPicker(input)) {
      input.focus();
    }
  });
  console.log("showPicker available:", typeof input?.showPicker === "function");
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

showPicker needs a browser DOM

What this snippet does

Input showPicker Feature Detection is built around the function openPicker.

Caveats

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • This is browser-side code — document will not resolve in Node.
  • The guard typeof input.showPicker !== "function" ends the flow early with a return when its condition holds.

Applying it

The signature of the main entry point: function openPicker(input: HTMLInputElement)

Printed tags correspond to steps: showPicker needs a browser DOM, showPicker available:.

Statements that matter

button?.addEventListener("click", () => {
  if (input && openPicker(input)) {
    input.focus();
  }
});
if (error instanceof TypeError) return false; // no picker for this input type
throw error;
if (typeof input.showPicker !== "function") return false;

Interactive Tools for This Topic

FAQ

Does Input showPicker Feature Detection run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.