I thought I’d share a useful snippit of jQuery code for scrolling to a specific element on a page.
$('html, body').animate({ scrollTop: ($('#element').offset().top) },500);
We use the .animate() method to scroll to the top of #element, over a period of 500 milliseconds.
jQuery To Scroll To The First Element With A Specific Class
A practical use of this could be in validating a form and you want to scroll to the first error for the user to correct. Assuming all elements with problems have been given the class of error, we can scroll to the first one using jQuery’s .first() method before chaining on .offset() and the property top as before.
$('html, body').animate({ scrollTop: ($('.error').first().offset().top) },500);
Now, go get scrolling!
Thanks, will try this out Monday; I’ve got large form and submit button is at bottom of page; and if this works would be great, as would direct the user to FIRST validation error. thanks
Thanks. good working your code.
Worked!!! Thanks a lot
Thank you brother for this best code :):):)
Thank you!