Forked from hirejordansmith/add-cursor-focus-first-gf-field-validation-error-all-forms.php
Last active
October 23, 2023 15:33
-
-
Save spivurno/ee1d3c157738e22e2cb44bf239eeffd2 to your computer and use it in GitHub Desktop.
Gravity Wiz // Gravity Forms // Give First Validation Error Focus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Gravity Wiz // Gravity Forms // Give First Validation Error Focus | |
* http://gravitywiz.com/ | |
* | |
* Plugin Name: Gravity Forms First Error Focus | |
* Plugin URI: https://gravitywiz.com/make-gravity-forms-validation-errors-mobile-friendlyer/ | |
* Description: Automatically focus (and scroll) to the first field with a validation error. | |
* Author: Gravity Wiz | |
* Version: 1.1 | |
* Author URI: http://gravitywiz.com/ | |
*/ | |
add_filter( 'gform_pre_render', 'gw_first_error_focus' ); | |
function gw_first_error_focus( $form ) { | |
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { | |
return $form; | |
} | |
add_filter( 'gform_confirmation_anchor_' . $form['id'], '__return_false' ); | |
?> | |
<script type="text/javascript"> | |
if( window['jQuery'] ) { | |
( function( $ ) { | |
$( document ).on( 'gform_post_render', function() { | |
// AJAX-enabled forms will call gform_post_render again when rendering new pages or validation errors. | |
// We need to reset our flag so that we can still do our focus action when the form conditional logic | |
// has been re-evaluated. | |
window['gwfef'] = false; | |
gwFirstErrorFocus(); | |
} ); | |
$( document ).on( 'gform_post_conditional_logic', function( event, formId, fields, isInit ) { | |
if( ! window['gwfef'] && fields === null && isInit === true ) { | |
gwFirstErrorFocus(); | |
window['gwfef'] = true; | |
} | |
} ); | |
function gwFirstErrorFocus() { | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure thing. This line can be updated like so: