Skip to content

Instantly share code, notes, and snippets.

@yunusga
Created July 5, 2019 06:46
Show Gist options
  • Save yunusga/94a0e66eeb1ef559fb25d8b49651e5c7 to your computer and use it in GitHub Desktop.
Save yunusga/94a0e66eeb1ef559fb25d8b49651e5c7 to your computer and use it in GitHub Desktop.
Scroll to first invalid field on Contact Form 7 validation error event
/**
* Scroll to first invalid field
* WPCF7 on validation error event
*/
document.addEventListener( 'wpcf7invalid', function( event ) {
setTimeout( function() {
$('html').stop().animate({
scrollTop: $('.wpcf7-not-valid').eq(0).offset().top - 140,
}, 500, 'swing');
}, 100);
}, false );
@paperplanefactory
Copy link

paperplanefactory commented Jul 25, 2023

Even better for accessibility, wait 3 seconds (so the screen reader can read the error message) and then move focus to the first input with an error. There is no need to add animations if the HTML CSS has the scroll-behavior property: smooth;

document.addEventListener('wpcf7invalid', function (event) {
  setTimeout(function () {
    $('#' + event.detail.unitTag + ' .wpcf7-not-valid').eq(0).focus();
  }, 3000);
}, false);

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