I have a long form with submit button at the bottom of the form. I have multiple input fields in the form marked with required attribute. So when one of the first few input fields are left blank and I scroll down to click submit, the error "Please fill out this field" came out correctly for the first error on top of the browser. However, I have to scroll up all the way to the top to enter the input. How can I make it automatically scroll up to focus on the first input error?
There's a simple way to do it with jQuery.
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
If you don't want animation, use .scrollTop()
instead:
$('html, body').scrollTop($("#target-element").offset().top);
Source: http://www.abeautifulsite.net/smoothly-scroll-to-an-element-without-a-jquery-plugin-2/
If you're opposed to jQuery, you could roll your own solution by using window.scrollTo()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With