Scroll to the first error on a Gravity Forms form

How to Scroll to the First Error On a Gravity Form

Scroll to the first error on a Gravity Form after form submission for a superior customer user experience with this handy WordPress code snippet.

Everyone hates filling out forms.

We hate it, even more, when we are told there is an error on the form after hitting the submit button.

Compound that with trying to find the darn field that’s generating the error and it’s maybe time to throw the laptop out the window.

Not quite but I hear your pain.

As developers, we try our best to give our clients the very best user experience and this little code snippet will win you a pat on the back every time.

How much of a better UI experience would it be, if your Gravity Form automatically scrolled to the first field causing the error and put the cursor in the field ready to type?

This is my Gravity Forms Scroll To The First Error function.

/**
* Jump to the first error after submission
*
* @param $form
* @return mixed
*/
function gf_scroll_to_first_error_focus( $form ) {
?>
<script type="text/javascript">
if( window['jQuery'] ) {
( function( $ ) {
$( document ).bind( 'gform_post_render', function() {
var $firstError = $( 'li.gfield.gfield_error:first' );
if( $firstError.length > 0 ) {
$firstError.find( 'input, select, textarea' ).eq( 0 ).focus();
document.body.scrollTop = $firstError.offset().top;
}
} );
} )( jQuery );
}
</script>
<?php
return $form;
}
add_action( 'gform_pre_render', 'gf_scroll_to_first_error_focus', 10, 1 );

You can add this code snippet to your theme/child theme functions.php file or include it in your next plugin that integrates with Gravity Forms.

If you need to call this from a class, simply replace the last line with add_action( ‘gform_pre_render’, array( $this, ‘gf_scroll_to_first_error_focus’ ), 10, 1 );

Let me know in the comments below if this was helpful.

Was this article helpful?
YesNo