5

I have a website that has one input field (like a search engine) and I use the HTML5 autofocus attribute on it.

But on very small screen sizes the soft keyboard that pops up on many devices obscures too much of the screen.

Is it possible to se the autofocus attribute in a CSS media query, so its only active on larger displays ?

I know I could set the focus with Javascript, but right now the pages doesn't use any Javascript and I would prefer to avoid it if its possible to use CSS for this.

1
  • 6
    If you really don't want to use JS, you could have two inputs (one with autofocus, the other one without it), and show one or the other with media queries. Hidden inputs don't get autofocus ;) Commented Mar 26, 2015 at 18:25

1 Answer 1

6

As suggested above in comments: Use two inputs and make the one hidden (display:none;). Then with a @media rule target screens that have a maximum width of 480px and make the hidden input visible (display:block;) and hide the other one.

CSS:

.smscreen {
  display: none; 
}

@media screen and (max-width: 480px) {
  .lgscreen {
    display: none;
  }

  .smscreen {
    display: block;
  }

}

See Example using CSS.


Otherwise, you can detect the window size with jQuery on page load, and if the screen is larger than 480px to use .focus() function on the input.

See Example using jQuery.

Sign up to request clarification or add additional context in comments.

6 Comments

The jQuery demo does not work. 1. You would also need to do it on page load (So you don't have to resize your window for it to work). 2. It seems that adding the attribute afterwards is not setting the focus. Since we don't care whether or not the input gets focus on window resize (mobile users don't resize their window), you could just .focus() it on page load if the screen size is large enough: codepen.io/anon/pen/wBOwep
Whoops, my bad. Thanks, for the tip. Can I include your pen for the jQuery example?
Mine, is working on resize. Open the console and resize the window to see it added and removed. The reason for not doing anything is a strange one, see here a working autofocus input and compare it to this here. Mind the spacing where the type="text" and autofocus in these two. So I assume is appending it like this one.
Nice catch! That is really weird indeed. Looks like a bug.
Yes, I am not sure what it is! I included your jquery solution and removed mine.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.