7

Using the HTML5 attribute "autofocus" can be a really useful thing for web pages. However, using - for example - Firefox (37.0.1) on Android devices results in the soft keyboard being displayed on page load.

<input type="text" name="q" autofocus>

The soft-keyboard takes up a lot of space and therefore I'd like to prevent this from opening. At the same time, autofocus is a very useful feature that we need for normal screens/devices.

I tried removing the "autofocus" attribute based on screen width via jQuery on page load, however, that's too late. At this point, the browser apparently already accepted the attribute and shows the soft keyboard:

$(function(){
    if (window.innerWidth < 600)
        $('*[autofocus]').removeAttr('autofocus');
});

Any suggestions?

Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97

1 Answers1

2

Try this, it works on desktop, I haven't test it on mobile. Delete the attribute autofocus

<input type="text" name="q">

and the JS

function setFocus() {
    if (window.innerWidth > 600)
        $("input[name=q]").focus();
}
$(document).ready(function() {
    setFocus();
});
Enrique Zavaleta
  • 2,098
  • 3
  • 21
  • 29
  • That sure works, but I'd prefer not to make changes on the markup itself. Unless another solutions pop up, I'll mark this as accepted later. – Simon Steinberger Apr 13 '15 at 15:56
  • Works great. However, I think it's better to check for the 'ontouchstart' event in the windows object instead of windows width. That's because resolutions grow pretty fast and the Samsung S6 already has a larger resolution than my 27" screen :-P – Simon Steinberger Apr 13 '15 at 22:01