How to adjust the text box is already in focus when my web page loads

I want the text box to be in focus when my web page loads. If you go to google.com, you will see that the text box is already in focus. This is what I want.

Here is my form:

<form id="searchthis" action="#" style="display:inline;" method="get"> <input id="namanyay-search-box" name="q" size="40" x-webkit-speech/> <input id="namanyay-search-btn" value="Search" type="submit"/> 
+4
source share
3 answers

Enter your text as an autofocus attribute. It has pretty good browser support, although not perfect. We can polyfill this functionality quite easily; I took the liberty of writing an example below. Just place this at the bottom of the document (so that the elements already exist when it starts up) and it will find your autofocus element (note: you should only have one , otherwise you could get inconsistent results ) and focus on it.

 (function () { // Proceed only if new inputs don't have the autofocus property if ( document.createElement("input").autofocus === undefined ) { // Get a reference to all forms, and an index variable var forms = document.forms, fIndex = -1; // Begin cycling over all forms in the document formloop: while ( ++fIndex < forms.length ) { // Get a reference to all elements in form, and an index variable var elements = forms[ fIndex ].elements, eIndex = -1; // Begin cycling over all elements in collection while ( ++eIndex < elements.length ) { // Check for the autofocus attribute if ( elements[ eIndex ].attributes["autofocus"] ) { // If found, trigger focus elements[ eIndex ].focus(); // Break out of outer loop break formloop; } } } } }()); 

After some initial testing, this seems to provide support all the way to Internet Explorer 6, Firefox 3, etc.

Optional test in your browser: http://jsfiddle.net/jonathansampson/qZHxv/show

+3
source

Jonathan Sampson's HTML5 solution is probably the best. If you are using jQuery, the sample sample should work too. To be complete, here you go with a simple JS solution for all browsers and IE10 +

 window.addEventListener("load",function() { document.getElementById("namanyay-search-box").focus(); }); 
+2
source
 $(document).ready(function(){ ..code.. $('.textbox-class-name').focus(); ..code.. }); 

Or you can try it on $(window).load()

0
source

All Articles