Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to the first input error of HTML5 form validation

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?

like image 232
Tony Vu Avatar asked May 18 '15 09:05

Tony Vu


1 Answers

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

like image 116
ohaal Avatar answered Oct 03 '22 23:10

ohaal