Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mecmartini/4af4c45a8011ad57ffbd7eb2c101448b to your computer and use it in GitHub Desktop.
Save mecmartini/4af4c45a8011ad57ffbd7eb2c101448b to your computer and use it in GitHub Desktop.
HTML5 form invalid hint scroll with fixed bar
function scrollToInvalid() {
// Height of your nav bar plus a bottom margin
var navHeight = $('header.navbar-fixed-top').height() + 20;
// Offset of the first input element minus your nav height
var invalid_el = $('input:invalid,select:invalid,textarea:invalid').first().offset().top - navHeight;
// If the invalid element is already within the window view, return true. If you return false, the validation will stop.
if ( invalid_el > (window.pageYOffset - navHeight) && invalid_el < (window.pageYOffset + window.innerHeight - navHeight) ) {
return true;
} else {
// If the first invalid input is not within the current view, scroll to it.
$('html, body').scrollTop(invalid_el);
}
}
$('input,select,textarea').on('invalid', scrollToInvalid);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment