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)
Use the setSelectionRange() method to move the cursor to the beginning of the input field. Call the focus() method on the input element. The focus method will move the cursor to the beginning of the element's value.
To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.
createTextRange();//Create a range (a range is a like the selection but invisible) range. moveToElementText(contentEditableElement);//Select the entire contents of the element with the range range. collapse(false);//collapse the range to the end point.
The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document. caretPositionFromPoint() method.
You 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With