manually trigger focus on input Iphone issue

12.2k views Asked by At

I am trying to focus a textarea after a click on a another element. desktop browsers seems to be working fine but not the Iphone.

$('.reveal_below').on('change', function(e) {

    e.preventDefault();
    var item_id = $(this).attr('data-item-id');
    if (this.checked) {

        $('.hidden_below__' + item_id).css({
                        'margin-left': '0px',
                        display: 'block',
                        opacity: '0'
                    }).animate({ 
                       'margin-left': '15px',
                        opacity: '1'
        }, 
 250, function() {
    console.log("-----------");
    $("#x").focus();
})
    } else {
        $('.hidden_below__' + item_id).slideUp();
    }
});

here is a little demo

it will focus a textarea on change event of the checkbox. That is the issue and how to can i solve this with the animation as in the demo?

1

There are 1 answers

1
Isuru Buddhika On BEST ANSWER

You have to use touchstart event to fix this issue.

$(document).ready(function() {

  $('button').on('click', function() {
    $('#x').css({
      'margin-top': '0px',
      display: 'block',
      opacity: '0'
    }).animate({
        'margin-top': '15px',
        opacity: '1'
      },
      100
    )

    $('#x').trigger('touchstart'); //trigger touchstart
  });

  $('textarea').on('touchstart', function() {
    $(this).focus();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>


<textarea id="x" style="width: 100%;height:6em;display: none" placeholder="Return notes..." cols="30" rows="10"></textarea>

<button type="button">focus textarea</button>