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 );
    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?

Keep In Touch With My Weekly Blog Email

A once-per-week daily digest of my posts from the week. No sales, no spam and I will not share your details with anyone else.


Wil is a dad, WordPress consultant, WordPress developer, business coach and mentor. He co-organizes the WordPress Sydney meetup group and has been on the organising committee for WordCamp Sydney since 2014. He speaks at many special events and contributes to the WordPress open source project. His likes are chillies, craft beer and electrogravitics.