Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent HTML5 autofocus from displaying soft-keyboard on smaller (mobile) screens

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?

like image 917
Simon Steinberger Avatar asked Apr 13 '15 14:04

Simon Steinberger


1 Answers

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();
});
like image 140
Enrique Zavaleta Avatar answered Oct 04 '22 23:10

Enrique Zavaleta