Auto-Focus Form Fields with jQuery
When you load a page that contains a form, it may be useful to automatically place the user’s cursor in the first form field. This post explains how to do autofocus with jQuery.
Basic autofocus
In your form, let’s say that you have some input field that you would like to autofocus for users. Something like:
<input type="text" name="name">
To auto-focus on this field when the page loads, we can use the following snippet of jQuery:
$('input[name="name"]').focus();
The trick here is .focus()
, which can be used to match any selector on the page.
Tricksy autofocus
As a bonus, here is a trick to autofocus a field based on the value of the #hash
fragment in the URL:
if ( window.location.hash == '#password' ) {
$('.password').focus();
}
I’ve used this snippet on projects where the user can reset his or her password. After the page refreshes and the reset-password email has been sent, the password field is automatically focused, ready for the user to enter their new password. Just one example of how this might be used!
Bonus!
Here is a bonus JavaScript snippet for autofocusing when the user hovers over the WordPress search field:
function focusElement() {
if (document.getElementById) {
document.getElementById('s').onmouseover = function() { document.getElementById('s').focus(); }
}
}
addDOMLoadEvent(focusElement);
As-is, this code targets the default WordPress search form. To target a different element, simply replace both instances of s
with the id of the target element.