I'm trying to customize the behavior of the HTML5 validation. I want invalid fields to scroll to the middle of the page when the user hits submit. My first attempt was to do this but it doesn't work:
$.each($("input, select"), function (index, input) {
input.addEventListener("invalid", function () {
this.scrollIntoView({
block: 'center',
behavior: 'smooth'
});
});
});
https://jsfiddle.net/gib65/j1ar87yq/
Calling scrollIntoView(...) with block center not working
It doesn't work because the default scrolling behavior, which is to scroll the invalid field to the top of the page instantly (i.e. not smooth), overrides the behavior I'm trying to specify in the scrollIntoView(...) options.
So then I tried this:
$.each($("input, select"), function (index, input) {
input.addEventListener("invalid", function (e) {
e.preventDefault();
this.scrollIntoView({
block: 'center',
behavior: 'smooth'
});
});
});
https://jsfiddle.net/gib65/527u1cm3
Adding preventDefault() allows the scrolling behavior I specified to happen. But it also prevents the invalid field from focusing and the validation message from appearing.
So my question is: is there a way to get the validation message to pop up WITHOUT scrolling?
Something like this:
$.each($("input, select"), function (index, input) {
input.addEventListener("invalid", function (e) {
e.preventDefault();
this.scrollIntoView({
block: 'center',
behavior: 'smooth'
});
this.focus();
this.showValidationMessage();
});
});
I've tried reportValidity() but that triggers the whole validation process which of course defeats the purpose (i.e. it will invoke the default scrolling which overrides my custom scrolling). I've also tried checkValidity() but this results in a "Maximum call stack size exceeded" probably because it fires the "invalid" event which causes the listener to pick it up again and repeat indefinitely.
Any help would be appreciated. Thanks.