How to Add Autofocus on Your Form

Overview

Would you like to have add autofocus on your form when the page loads? This is easily done by adding a small code snippet to your site. In this tutorial, we’ll show you the JavaScript needed to have achieve this.

Setup

In order to implement this, copy and paste this small code snippet to your site.

/**
 * Add autofocus to first form field of form
 *
 * @link https://wpforms.com/developers/how-to-add-autofocus-on-your-form/
 *
 */

function wpf_dev_autofocus() {
    ?>
    <script type="text/javascript">
jQuery(document).ready(function() {
    var first_input = jQuery('form.wpforms-form input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];
    if(first_input != undefined){ first_input.focus(); }
});
	</script>
<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_autofocus' );

This code snippet will only apply to WPForms because it’s only looking for forms.wpforms-form and will look for the first form field on your form and immediately add the :focus element to this field.

Now when the page loads the field will now automatically autofocus on the first form field

And that’s it! You’ve successfully implemented the autofocus functionality on all of your forms powered by WPForms. Would you like to add some CSS that will make that focus stand out more? Check out our article on How to Add CSS to the Form Field Focus.

Action Reference: wpforms_wp_footer

FAQ

Q: How can I keep the autofocus active on a multi page form?

A: If you have a multi page form, just use this code snippet.

/**
 * Add autofocus to first form field of form
 *
 * @link https://wpforms.com/developers/how-to-add-autofocus-on-your-form/
 *
 */
function wpf_dev_autofocus() {
    ?>
    <script type="text/javascript">
		jQuery(document).ready(function() {
			var first_input = jQuery('form.wpforms-form input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];
			if(first_input != undefined){ first_input.focus(); }
			jQuery('.wpforms-page-next').on( "click", function() {
			  var page_first_input = jQuery(this).closest('.wpforms-page').next().find('input, textarea').first();
				if(page_first_input != undefined){ 
					setTimeout(function() { page_first_input.focus(); }, 100);
				}
			});
		});
    </script>
<?php
}
add_action( 'wpforms_wp_footer', 'wpf_dev_autofocus' );