Created
July 5, 2019 06:46
-
-
Save yunusga/94a0e66eeb1ef559fb25d8b49651e5c7 to your computer and use it in GitHub Desktop.
Scroll to first invalid field on Contact Form 7 validation error event
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
/** | |
* 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 ); |
Better to use:
document.addEventListener( 'wpcf7invalid', function( event ) { setTimeout( function() { $('html').stop().animate({ scrollTop: $('#' + event.detail.unitTag + ' .wpcf7-not-valid').eq(0).offset().top - 140, }, 500, 'swing'); }, 100); }, false );In this case, there will be no problems if there is more than one form on the page.
I adapted your code to Vanilla JS:
document.addEventListener( 'wpcf7invalid', function( event ) {
setTimeout( function() {
document.querySelector('.wpcf7-not-valid').scrollIntoView();
}, 100);
}, false );
document.addEventListener( 'wpcf7invalid', function( event ) { setTimeout( function() { document.querySelector('.wpcf7-not-valid').scrollIntoView(); }, 100); }, false );
You have forgot animation.
document.addEventListener(
"wpcf7invalid",
function (event) {
setTimeout(function () {
document.querySelector(".wpcf7-not-valid").scrollIntoView({
behavior: "smooth",
// block: "nearest",
// inline: "nearest"
});
}, 100);
},
false
);```
Hello,
How can it be used? Where does it go?
Thank you!
Code for pages with fixed scrollbar
"wpcf7invalid",
function (event) {
setTimeout(function () {
var element = document.querySelector(".wpcf7-not-valid");
var elementPosition = element.getBoundingClientRect().top;
var offset = 140; // Setzen Sie hier den gewünschten Offset-Wert
var newPosition = elementPosition + window.pageYOffset - offset;
window.scrollTo({
top: newPosition,
behavior: "smooth"
});
}, 100);
},
false
);
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
Better to use:
In this case, there will be no problems if there is more than one form on the page.