Matheus Battisti
Matheus Battisti

Reputation: 31

How activate iOS keyboard focusing on an input after clicking in a button?

I am developing a search module, and stuck in this functionality, the logic is:

user click on a lens icon and focus in input showing the keyboard

on android this works fine, just putting:

jQuery('input').focus();

but on iOS, this dont work, the input shows but dont focus, and keyboard does not appear, any ideas?

Upvotes: 2

Views: 2585

Answers (3)

Viktor Makoed
Viktor Makoed

Reputation: 21

After searching and testing some working options I found this:

$(function() {
  function focus() {
    $('#input').focus();
  }

  $(document.body).load($(focus));
  $('#button').click(focus); // click on the #button element will focus #input and show iOS keyboard
});

http://jsfiddle.net/hgxj5yue/

Upvotes: 2

James Lawruk
James Lawruk

Reputation: 31335

Here is a hacky work-around.

Position your input over top the lens icon button. Set the input container to a similar width as your button and set the opacity to 0 so it is invisible. Something like this:

div.input-container {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 60px;    
    z-index: 1000;    
    opacity: 0;
}

Then when the user clicks on the button, they are actually clicking inside the input, which will set the focus natively. Add an input click event handler to set the opacity to 1 set the input width to its proper size.

inputField.addEventListener('click', (event) => {
   //use Jquery or plain JS to add a search-mode class to unhide the input
});

div.input-container.search-mode {            
    width: 100%;                 
    opacity: 0;
}

You will also have to add a way to remove the search-mode css class to get the input field back to its initial hidden state.

Upvotes: 0

lshettyl
lshettyl

Reputation: 8181

You may want to use touchstart for it to work on iOS (this should also work on Android). Within the click handler, trigger touchstart on the input. I assume myinput as the class of your input.

$('input.myinput').trigger('touchstart');

$('input.myinput').on('touchstart', function() {

    $(this).focus();

})

Upvotes: 0

Related Questions