Magento2 – Scroll to First Input Error Validation Message on Checkout

checkoutjavascriptknockoutjsmagento2

I saw some simillar questions, but they wanted to remove this feature. They suggested to comment some code in MAGENTO_ROOT/vendor/magento/magento2-base/lib/web/mage/validation.js file

if (firstActive.length) {
                $('html, body').animate({
                    scrollTop: firstActive.offset().top
                });
                firstActive.focus();
            }

the part with animate, but actually in my vendor file this code was not there. So i added in my file since I want this feature. But nothing happens, when continue button on checkout is pressed and I have errors in form, the body doesn't scroll to the invalid input. On desktop it's ok, but on mobile, the user might never see the error.

I've also tried to put in my JavaScript file, some custom code, some jquery, when the button is clicked. I thought initial that it doesn't work because the button is already having the onclick event from magento files, from knockout. But i think that my jquery is not working because the element are not there, and the functions is triggered before the html elements load in dom.

enter image description here

Best Answer

Try something like this

    require(['jquery', 'domReady!'], function($){
        $(document).on('click','body .action.primary.continue', function(){
            if($('._required._error:visible:first').offset() !== undefined) {
                $('html, body').animate({
                    scrollTop: $('._required._error:visible:first').offset().top
                }, 500);
            }
        });
    });
Related Topic