Mobile Safari: Javascript focus() method on inputfield only works with click?

mobile safari focus input
safari focus not working
ios force keyboard to show javascript
ios input focus issue
ios focus text field programmatically
input field not working on iphone
focus not working
javascript open keyboard mobile

I have a simple input field like this.

<div class="search">
   <input type="text" value="y u no work"/>
</div>​

And I'm trying to focus() it inside a function. So inside of a random function (doesn't matter what function it is) I have this line …

$('.search').find('input').focus();

This works just fine on every Desktop whatsoever.

However it doesn't work on my iPhone. The field is not getting focused and the keyboard is not shown on my iPhone.

For testing purposes and to show you guys the problem I did a quick sample:

$('#some-test-element').click(function() {
  $('.search').find('input').focus(); // works well on my iPhone - Keyboard slides in
});

setTimeout(function() {
  //alert('test'); //works
  $('.search').find('input').focus(); // doesn't work on my iPhone - works on Desktop
}, 5000);​

Any idea why the focus() wouldn't work with the timeout function on my iPhone.

To see the live example, test this fiddle on your iPhone. http://jsfiddle.net/Hc4sT/

Update:

I created the exact same case as I'm currently facing in my current project.

I have a select-box that should — when "changed" — set the focus to the input field and slide-in the kexboard on the iphone or other mobile devices. I found out that the focus() is set correctly but the keyboard doesn't show up. I need the keyboard to show up.

Actually, guys, there is a way. I struggled mightily to figure this out for [LINK REMOVED] (try it on an iPhone or iPad).

Basically, Safari on touchscreen devices is stingy when it comes to focus()ing textboxes. Even some desktop browsers do better if you do click().focus(). But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions:

1) The user clicked somewhere and focus() was called while executing the click event. If you are doing an AJAX call, then you must do it synchronously, such as with the deprecated (but still available) $.ajax({async:false}) option in jQuery.

2) Furthermore -- and this one kept me busy for a while -- focus() still doesn't seem to work if some other textbox is focused at the time. I had a "Go" button which did the AJAX, so I tried blurring the textbox on the touchstart event of the Go button, but that just made the keyboard disappear and moved the viewport before I had a chance to complete the click on the Go button. Finally I tried blurring the textbox on the touchend event of the Go button, and this worked like a charm!

When you put #1 and #2 together, you get a magical result that will set your login forms apart from all the crappy web login forms, by placing the focus in your password fields, and make them feel more native. Enjoy! :)

(Sort of) Fixing autofocus in iOS Safari - Tommy Brunn, Oh well, no big deal, we can fix that with a little bit of Javascript. .focus() }). To your great surprise, you discover that this is not working either! Not only is the autofocus attribute not supported, but you have in fact made the you some groundbreaking new front-end technique, but just to share some of  But the designers of Safari on touchscreen devices realized it's annoying to users when the keyboard keeps coming up, so they made the focus appear only on the following conditions: 1) The user clicked somewhere and focus() was called while executing the click event.

A native javascript implementation of WunderBart's answer.

Disable auto zoom using font size.

function onClick() {

  // create invisible dummy input to receive the focus first
  const fakeInput = document.createElement('input')
  fakeInput.setAttribute('type', 'text')
  fakeInput.style.position = 'absolute'
  fakeInput.style.opacity = 0
  fakeInput.style.height = 0
  fakeInput.style.fontSize = '16px' // disable auto zoom

  // you may need to append to another element depending on the browser's auto 
  // zoom/scroll behavior
  document.body.prepend(fakeInput)

  // focus so that subsequent async focus will work
  fakeInput.focus()

  setTimeout(() => {

    // now we can focus on the target input
    targetInput.focus()

    // cleanup
    fakeInput.remove()

  }, 1000)

}

How to set focus in Safari on iOS, or determine that you can't, I gave up on this, as it requires a code fix (sp. safari) which might/might not [1] Mobile Safari: Javascript focus() method on inputfield only works with click? Mobile Safari: Javascript focus() method on inputfield only works with click. Running this fiddle in Mobile Safari or Chrome on iOS will confirm this answer. $("input").focus(); // Does not focus input in Mobile Safari or Chrome on iOS. This code has been tested (and failed) in Mobile Safari and Chrome on iOS on the following devices:

I faced the same issue recently. I found a solution that apparently works for all devices. You can't do async focus programmatically but you can switch focus to your target input when some other input is already focused. So what you need to do is create, hide, append to DOM & focus a fake input on trigger event and, when the async action completes, just call focus again on the target input. Here's an example snippet - run it on your mobile.

edit:

Here's a fiddle with the same code. Apparently you can't run attached snippets on mobiles (or I'm doing something wrong).

var $triggerCheckbox = $("#trigger-checkbox");
var $targetInput = $("#target-input");

// Create fake & invisible input
var $fakeInput = $("<input type='text' />")
  .css({
    position: "absolute",
    width: $targetInput.outerWidth(), // zoom properly (iOS)
    height: 0, // hide cursor (font-size: 0 will zoom to quarks level) (iOS)
    opacity: 0, // make input transparent :]
  });

var delay = 2000; // That's crazy long, but good as an example

$triggerCheckbox.on("change", function(event) {
  // Disable input when unchecking trigger checkbox (presentational purpose)
  if (!event.target.checked) {
    return $targetInput
      .attr("disabled", true)
      .attr("placeholder", "I'm disabled");
  }

  // Prepend to target input container and focus fake input
  $fakeInput.prependTo("#container").focus();

  // Update placeholder (presentational purpose)
  $targetInput.attr("placeholder", "Wait for it...");

  // setTimeout, fetch or any async action will work
  setTimeout(function() {

    // Shift focus to target input
    $targetInput
      .attr("disabled", false)
      .attr("placeholder", "I'm alive!")
      .focus();

    // Remove fake input - no need to keep it in DOM
    $fakeInput.remove();
  }, delay);
});
label {
  display: block;
  margin-top: 20px;
}

input {
  box-sizing: border-box;
  font-size: inherit;
}

#container {
  position: relative;
}

#target-input {
  width: 250px;
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
  <input type="text" id="target-input" placeholder="I'm disabled" />

  <label>
    <input type="checkbox" id="trigger-checkbox" />
    focus with setTimetout
   </label>
</div>

Programmatically focus on next input field in mobile safari, Now, on desktop browser the cursor jumps to the next input field whenever a char is point $('button').on('click', function () { // trigger touch on element to set focus Mobile Safari: Javascript focus() method on inputfield only works , Actually,  This problem is on iPad IOS6 in mobile Safari. I wan´t the text in an input to be auto selected when the user clicks the input. I have a solution that works in a regular browser, like Chrome:

I have a search form with an icon that clears the text when clicked. However, the problem (on mobile & tablets) was that the keyboard would collapse/hide, as the click event removed focus was removed from the input.

Goal: after clearing the search form (clicking/tapping on x-icon) keep the keyboard visible!

To accomplish this, apply stopPropagation() on the event like so:

function clear ($event) {
    $event.preventDefault();
    $event.stopPropagation();
    self.query = '';
    $timeout(function () {
        document.getElementById('sidebar-search').focus();
    }, 1);
}

And the HTML form:

<form ng-controller="SearchController as search"
    ng-submit="search.submit($event)">
        <input type="search" id="sidebar-search" 
            ng-model="search.query">
                <span class="glyphicon glyphicon-remove-circle"
                    ng-click="search.clear($event)">
                </span>
</form>

Annoying iOS Safari input issues with workarounds, now, to create forms that both improves the UX and works properly is still a tough grind. When a read-only text input field gets focus, the virtual keyboard This was tested by using plain javascript code: addEventListener('click', function () { logEvent('click on input ' + nr); }); } var console = document. iOS focus on input field only brings up keyboard when called inside a click handler. It doesn’t work if the focus is async. This presents a curious problem when you want to autofocus an input inside a modal or lightbox, since what you generally do is click on a button to bring up the lightbox, and then focus on the input after the lightbox

This solution works well, I tested on my phone:

document.body.ontouchend = function() { document.querySelector('[name="name"]').focus(); };

enjoy

iOS does not show keyboard on .focus() · Issue #3016 · jquery , When I call .focus() on one of my text inputs or textareas, the iPhone As far as I know it isn't possible to show the iOS keyboard via javascript. following code works on my mobile Safari, Chrome and also desktop preventDefault(); }) }; var mobile = false; div.on('click', function(event) { if(mobile) return;  Notes. If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement; Behaviour of the focus in relation to different HTML features like tabindex or shadow dom, which previously remained under-specified, were recently updated (as October of 2019).

Focus is not working in iOS devices · Issue #15317 · angular , What is the expected behavior? setting focus should work across all What are the steps to reproduce? add a input field into angular So i moved ngAfterViewChecked() code to ngAfterViewInit() but it didn't work on mobile devices. It sets the focus and shows keyboard on a button click event but not  click – Opens the widget on pointer click (desktop, or hybrid devices). focus – Opens the widget when the navigation between page elements is done with keyboard or assistive technologies (VoiceOver, TalkBack…).

.focus() within iOS mobile is not opening keyboard, In order to be able to use javascript to focus an input in IOS, you This one works well. document.body.ontouchend = function() { document. Click on the different category headings to find out more and change our default settings. They are usually only set in response to actions made by you which  hopefully this [1] should resolve your issue. I gave up on this, as it requires a code fix (sp. safari) which might/might not affect behavior on other browsers (don

HTMLElement.focus(), Click me to focus on the text field! Focus on a button. JavaScript. focusMethod = function getFocus()  When you touch an item on a webpage, it first triggers a hover state and then triggers the “click”. The end result is that you end up seeing styles applied using :hover for a second before the click interaction happens. It’s a little startling, but it does work.

Comments
  • maybe it is focused, but the keyboard just doesn't show up (that's the case on my Nokia X6).
  • works for me. jsfiddle you pasted just focused the box and opens a keyboard on my iphone. which iOS are you using? I've checked with 5.1.
  • Ok, you're right as it seems. I'm on iOS 5.1.1. The focus() seems to work as I know set input:focus { background:green; } via css on the input. However the keyboard doesn't slide-in for me. See this work case I'm currently working on. cl.ly/1d210x1W3Y3W Test this on your iPhone. Any chance to slide in the keyboard when choosing "Search" in the select-box?
  • I am trying alot of things. I tried triggerHandler(), focusin(), trigger("focus"). I even tried to blur it first and then re-add the focus. I think it might be a bug in webkit. You might be out of luck with this one...But I am going to try a couple more things...
  • I am giving up. I tried everything. It's just not something you can do in the iOS Safari Web browser. Hopefully Apple makes a change to allow this because I certainly don't consider this a "feature"! haha I don't know why you can so easily blur() the field but can't set focus to it. Doesn't make sense to me.
  • This sounds very intelligent, but I'm having a hard time "putting #1 and #2 together". In my app, using jQueryMobile, when a user clicks on a list item in page A, a new page B opens which has just one visible input. I want the keyboard to open automatically for that input. Do you mean to say I must put the .focus() call somewhere in the click handler on page A?
  • Thank you for saving my time. That was so unobvious to find.
  • I was able to get it! Instead of blurring and focusing the element, I simply added event.preventDefault() on touchstart. Note that this prevents the ng-click from executing, so I had to add my clear text logic inside the event handler and $scope.$apply()
  • I found that just running input.focus() from a button's click handler, worked. Safari on iPhone 5 and iPad. If I had the focus() in a setTimeout, that didn't work. So maybe that's what "synchronously" means, @Michael.
  • Thank you for posting an actual solution. Blurring previous element on touchend + setting focus on click event does work in iOS10 still.