Posted 2019-04-04 with tags HTML, HTML Validation, jQuery, Snippet

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);

Helpful Links

  • https://stackoverflow.com/questions/19814673/html5-input-required-scroll-to-input-with-fixed-navbar-on-submit/30247982