javascripthtmlmobile

Manually bringing up keyboard on mobile


I'm making a hangman game in javascript and html. Currently I have it so the program just listens for keystrokes as the input.

document.onkeyup = function() {
        var guess = event.key;

I just discovered that on a mobile device, the keyboard won't pop up automatically. Is there anyway to get it to pop up manually if it detects that it's on a mobile device, without changing the code to take in prompts() instead of keystrokes?

Thanks!


Solution

  • Focusing on input element is what get Mobile to show keyboard.

    So you should try to manually focus on some random element which if not needed can be hidden. (See HTMLElement.focus())

    For example, this JS:

    const textField = document.getElementById("myTextField");
    const focusBtn = document.getElementById(`focusBtn`);
    focusBtn.addEventListener(`click`, () => textField.focus());
    

    plus this HTML:

    <input type="text" id="myTextField" value="Text field.">
    <p></p>
    <button id="focusBtn">Click me to focus on the text field!</button>