Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing cursor to go on text field

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)

like image 612
David542 Avatar asked Apr 02 '11 04:04

David542


People also ask

How do I set the input field cursor?

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.

How do I change the cursor position in textarea?

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.

How do you move the cursor to the end of Contenteditable entity?

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.

What is caret position in Javascript?

The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document. caretPositionFromPoint() method.


2 Answers

You need to use JavaScript. e.g.

<input type="text" id="search" />
<script type="text/javascript">
document.getElementById('search').focus()
</script>
like image 125
bradley.ayers Avatar answered Nov 02 '22 22:11

bradley.ayers


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

like image 38
Tim Down Avatar answered Nov 02 '22 23:11

Tim Down