Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS show keyboard on input focus

I have a problem that i can't fix.

Keyboard doesn't show on input.focus() on IOS

 searchMobileToggle.addEventListener('click', function() {
       setTimeout(function(){
          searchField.focus();
       }, 300);
    });

I've been looking for a solution with no result, i know this is a frequently unsolved question but i see NIKE (https://m.nike.com/fr/fr_fr/) and FOODSPRING (https://www.foodspring.fr/) doing it on mobile.

So i'm wondering how do they do ?

like image 890
Mibuko Avatar asked Jan 29 '19 15:01

Mibuko


1 Answers

None of the other answers worked for me. I ended up looking into the Nike javascript code and this is what I came up with as a reusable function:

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();

    // The keyboard is open. Now do a delayed focus on the target element
    setTimeout(function() {
      el.focus();
      el.click();
      // Remove the temp element
      document.body.removeChild(__tempEl__);
    }, timeout);
  }
}

// Usage example
var myElement = document.getElementById('my-element');
var modalFadeInDuration = 300;
focusAndOpenKeyboard(myElement, modalFadeInDuration); // or without the second argument

Note that this is definitely a hacky solution, but the fact that Apple hasn't fixed this in so long justifies it.

like image 101
n8jadams Avatar answered Sep 19 '22 23:09

n8jadams