javascripthtmlcssfocusvirtual-keyboard

How to prevent auto focus on text elements when they become visible?


I have an html <dialog> tag with a text field in it. But when the dialog is opened the text field immediately gains focus. Which is fine on desktop devices, but on mobile this causes the virtual keyboard to pop up.

Is there a way to prevent the text field from gaining focus? Note that I'd still like the user to be able to focus after the dialog has become visible.

<dialog id="myDialog">
  Say something nice:
  <input type="text">
</dialog>
<button onclick="myDialog.showModal()">Open</button>


Solution

  • Seems like one way to do this is to make the text field disabled and then enable it again once the dialog is visible. Not sure if there's a more elegant way than this.

    <dialog id="myDialog">
      Say something nice:
      <input id="text" type="text" disabled>
    </dialog>
    <button onclick="myDialog.showModal(); text.disabled = false;">Open</button>