Forked from spivurno/gw-gravity-forms-first-error-focus.php
Created
April 27, 2020 12:25
-
-
Save version-control/0be697419d31401b5db010b16669c3fc 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 ) { | |
add_filter( 'gform_confirmation_anchor_' . $form['id'], '__return_false' ); | |
?> | |
<script type="text/javascript"> | |
if( window['jQuery'] ) { | |
( function( $ ) { | |
$( document ).bind( '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 ).bind( '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(); | |
$firstError[0].scrollIntoView(); | |
} | |
} | |
} )( jQuery ); | |
} | |
</script> | |
<?php | |
return $form; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment