Search code examples
jquery-validation-engine

jquery-validation-engine scroll to first error


I have a page where we have a fixed banner at the top, then a scrolling section down below that fixed banner. In this scrolling section, we have the form we are validating. If I have an error with a field earlier in the form, that is current scrolled up into the banner ( or maybe even above the banner ), it does not scroll to the first error field correctly. How do I resolve this type of problem?

I have three screen shots to better explain what I mean. I could not post the images themselves, so posted links to the images.

Figure 1: Before submitting form

Figure 2: After submitting form, bad scrolling. It goes to first error field, just not scrolled correctly

EDIT ( 04/18/2014 ): I can confirm that this code from jquery.validationEngine.js is what is not working. Basically, no matter what I set "destination" to, it still scrolls to the top of the window, NOT the top of the container all this stuff is in. Even if I force "destination" to be some huge number, it is like it ignores it. Should this jQuery plugin be doing things differently?

    $("html, body").animate({
                scrollTop: destination
            }, 1100, function(){
                if(options.focusFirstField) first_err.focus();
            });
            $("html, body").animate({scrollLeft: fixleft},1100);

Solution

  • Ok, I now have an even better fix. In the same section of code, I applied the below changes:

    _validateFields: function(form) {
                    ...... // code removed for the sake of brevity, but enough include to show context.
        if (errorFound) {
            if (options.scroll) {
                var errorfld = first_err; // This is the first change, at around line 371 in the original code.
                var fixleft = first_err.offset().left;
    
                //prompt positioning adjustment support. Usage: positionType:Xshift,Yshift (for ex.: bottomLeft:+20 or bottomLeft:-20,+10)
                var positionType=options.promptPosition;
                if (typeof(positionType)=='string' && positionType.indexOf(":")!=-1)
                    positionType=positionType.substring(0,positionType.indexOf(":"));
    
                if (positionType!="bottomRight" && positionType!="bottomLeft") {
                    var prompt_err= methods._getPrompt(first_err);
                    if (prompt_err) {
                        errorfld = prompt_err;
                    }
                }
    
                var destination= form.scrollTop() + ( errorfld.offset().top - form.position().top ) + ( errorfld.height()/2 );
    

    Once again, I am not sure if this will work in all uses of the jquery.validationEngine.js plugin, but it works in my case. If anyone else has a better idea, do tell me.