Last active
June 1, 2018 16:37
-
-
Save mecmartini/4af4c45a8011ad57ffbd7eb2c101448b to your computer and use it in GitHub Desktop.
HTML5 form invalid hint scroll with fixed bar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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