简体   繁体   中英

How to make default focus on the search bar on a web page, as Google does

I am trying to make a website. It is nearly completed, just a few details to be done.

I have a small problem and wasn't able to find the solution on internet.

When the index page on the site is loaded I want the focus to be on the search bar automatically, so that a person can just load the page and start typing in order to search.

The site has the jquery library included.

您可以使用autofocus属性完成此操作:

<input type="text" name="searchbar" autofocus />

Try like this:

<input type="text" autofocus="autofocus" />

or

try tabindex="1"

If you want to use jQuery:

<script> $(function(){ $('#elementID').focus(); }); </script>

Or in pure HTML:

<input type="search" autofocus="autofocus">

but that requires browser supporting HTML5 autofocus attribute, so jQuery solution is more realiable.

You can do this with below 3 methods, may these helps you :

1) <input type="text" id="search" name="search" autofocus />

2) $(function(){ $("#search").focus(); });

3) window.onload = function() { document.getElementById("search").focus(); }; window.onload = function() { document.getElementById("search").focus(); };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM