Compensating for Fixed Elements When Using Native HTML 'required' Validation using jQuery

When using the native html required directive (or any of the other validation directives), the resulting validation error message does not into account the presence of a fixed header. This can cause the the invalid element to be hidden behind the fixed navbar. To compensate for the fixed element, use the following bit of js/jquery which will adjust the scroll position to account for the fixed element:

document.addEventListener('invalid', function(event){
       $(event.target).addClass("invalid");
          // 150px height, 0 delay; configure based on your needs
          $('html, body').animate({scrollTop: $($(".invalid")[0]).offset().top - 150}, 0);
}, true);
document.addEventListener('change', function(event){
       $(event.target).removeClass("invalid")
}, true);

Tags

 HTML  HTML Validation  jQuery  Snippet 
Table of Contents