How do I make it so when my web page loads, the cursor automatically goes to a given text field? (For example, on Google when you load the page, the blinking cursor is already on the search box)
How do I make it so when my web page loads, the cursor automatically goes to a given text field? (For example, on Google when you load the page, the blinking cursor is already on the search box)
Share Improve this question edited Apr 2, 2011 at 4:31 bradley.ayers 38.4k14 gold badges98 silver badges101 bronze badges asked Apr 2, 2011 at 4:24 David542David542 110k203 gold badges564 silver badges1k bronze badges4 Answers
Reset to default 12You need to use JavaScript. e.g.
<input type="text" id="search" />
<script type="text/javascript">
document.getElementById('search').focus()
</script>
Be careful implementing this functionality. It's very annoying for a user to focus on a field and start typing only to find the caret has been redirected while typing when the page finished loading. I've seen this happen on numerous sites.
I'd suggest using the HTML5 autofocus
attribute and falling back to a JavaScript solution in browsers which don't support it. The following gets round the above problem by not waiting for the document to load before setting the focus:
<input type="text" name="search" id="search" autofocus>
<script type="text/javascript">
var input = document.getElementById("search");
if ( !("autofocus" in input) ) {
input.focus();
}
</script>
More information can be found at diveintohtml.org: http://diveintohtml5.ep.io/forms.html#autofocus
Try
<body onLoad="document.form1.txtBox1.focus()">
Since HTML5 is in full force, I believe autofocus
is well supported. I would take heed to the other answers here, but in my opinion, much easier than JavaScript:
<input type="text" name="name" autofocus>