80 words
1 minute
Scroll page to form if there are errors

Scroll page to form if there are errors#

For a Django application I’m working on (this issue) I have a form that can be quite a long way down the page.

If the form is displayed with errors, I want to scroll the user down to the form so they don’t get confused.

Since Django forms display errors in an element with a errorlist class, this worked:

window.addEventListener("load", () => {
if (document.querySelector('.errorlist')) {
document.querySelector('#my-form').scrollIntoView();
}
});

Element.scrollIntoView() on MDN, and on Can I use.

Scroll page to form if there are errors
https://mranv.pages.dev/posts/scroll-page-to-form-if-there-are-errors/
Author
Anubhav Gain
Published at
2024-03-25
License
CC BY-NC-SA 4.0