1

I've been trying to show up the keyboard on Safari web browser when focusing on an element. I want to display the keyboard without user action in the UI.

I've followed the example provided here: IOS show keyboard on input focus

But is still not working :(

This is my HTML:

<body>
    <div className="ModalBody">
        This is the body of the modal. Edit this "HTML" to play with the
        contents of the modal body.
        <br />
        <br />
        <label>
          The first input focuses automatically
          <br />
          <input type="text" />
        </label>
      </div>
</body>

This is my JS:

function focusAndOpenKeyboard(el, timeout) {
if(!timeout) {
    timeout = 100;
}
if(el) {
    // Align temp input element approximately where the input element is
    // so the cursor doesn't jump around
    var __tempEl__ = document.createElement('input');
    __tempEl__.style.position = 'absolute';
    __tempEl__.style.top = (el.offsetTop + 7) + 'px';
    __tempEl__.style.left = el.offsetLeft + 'px';
    __tempEl__.style.height = 0;
    __tempEl__.style.opacity = 0;
    // Put this temp element as a child of the page <body> and focus on it
    document.body.appendChild(__tempEl__);
    __tempEl__.focus();
    __tempEl__.click();

    // The keyboard is open. Now do a delayed focus on the target element
    setTimeout(function() {
    el.focus();

    // Remove the temp element
    document.body.removeChild(__tempEl__);
    }, timeout);
}
}

var firstInputEl = document.querySelector("input, textarea");


if (firstInputEl) {
    focusAndOpenKeyboard(firstInputEl, 300);
  }

The element ends up focused but the keyboard is not showing up on my iPhone.

Any ideas? Thanks!

Arasuvel
  • 2,971
  • 1
  • 25
  • 40

1 Answers1

0

This is my reusable function:

/**
 * iOS keyboard can only be opened by user interaction + focus event.
 * There are situations in which we need to open keyboard programmatically
 * before other elements are rendered, like when opening an overlay. this function can be used
 * to open the keyboard before the overlay is rendered, and once the overlay is
 * rendered, it's needed to focus to the desired input element, and the keyboard
 * will stay open.
 *
 * This function needs to be called from native events attached to HTML elements. It will
 * not work if called from a "passive" event, or after any event not coming from
 * user interaction (onLoad, onFocus, etc).
 *
 * It's recommended to use it on MouseEvents or TouchEvents.
 */
export function openIosKeyboard() {
    const input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("style", "position: fixed; top: -100px; left: -100px;");
    document.body.appendChild(input);
    input.focus();
    // it's safe to remove the fake input after a 30s timeout
    setTimeout(() => {
        document.body.removeChild(input);
    }, 30 * 1000);
}
Soldeplata Saketos
  • 3,212
  • 1
  • 25
  • 38