jqueryfocusonfocusjquery-form-validatorerrorplacement

how to control scroll location to locate displayed error return from jQuery AJAX


I would like to lower the returned error text into view, or lower the focus of the input field by about 150px from the top, because as it stands the error text is not visible.

I am using https://jqueryvalidation.org/ for my form validation, and call the validation like this:

$("form#option1").validate({
    lang: 'de'
});

I am using this to hide and show the navigation bar

function hasScrolled() {
    var st = $(this).scrollTop();
    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;
    
    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('#header_phone').removeClass('nav-down').addClass('nav-up');
        $('#header_ipad').removeClass('nav-down').addClass('nav-up');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('#header_phone').removeClass('nav-up').addClass('nav-down');
            $('#header_ipad').removeClass('nav-up').addClass('nav-down');
        }
    }
    lastScrollTop = st;
}

I got the navigation to hide by adding this to the submit button, and would like to now push the error text into view with some function.

$( "#RequestQuote" ).click(function() {
    setTimeout(function() {
        $('#header_phone').removeClass('nav-down').addClass('nav-up');
        $('#header_ipad').removeClass('nav-down').addClass('nav-up');   

        // move selected in focus element x mount from top  
        
    }, 100);
});

The error text above the field is held with this:

<label for="fieldname" generated="true" class="error"></label>

Solution

  • I got it working:

    var validator1 = $("form#option1").validate({
            lang: 'de', 
            focusInvalid: false, 
            invalidHandler: function(form, validator) {
    
                if (!validator.numberOfInvalids())
                    return;
    
                $('html, body').animate({
                    scrollTop: $(validator.errorList[0].element).offset().top-140
                }, 1200);
                
            }
        });