Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save spivurno/ee1d3c157738e22e2cb44bf239eeffd2 to your computer and use it in GitHub Desktop.
Save spivurno/ee1d3c157738e22e2cb44bf239eeffd2 to your computer and use it in GitHub Desktop.
Gravity Wiz // Gravity Forms // Give First Validation Error Focus
<?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;
}
@jandreaucodes
Copy link

Looks like the <script> tag here causes an error of Cannot modify header information - headers already sent by as of WordPress 5.5

@spivurno
Copy link
Author

@spivurno
Copy link
Author

@jandreaucodes I wasn't able to recreate your issue; however, I made some general improvements to the way this snippet-plugin loads the script that I suspect will resolve the issue for you.

@jandreaucodes
Copy link

That worked a treat, thanks.

Can I add some sort of offset to the error targeting? It seems to scroll a bit off the screen so the top of the error messaging is hiding behind the menu now.

@spivurno
Copy link
Author

spivurno commented Oct 21, 2020

Sure thing. This line can be updated like so:

document.body.scrollTop = $firstError.offset().top + 99;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment