Skip to main content

Scroll to first error

Help users find and fix validation errors by taking the user to the first validation error. Don't rely on using colour to show error, use text to describe it.

This field is required
Do you agree to these terms?
<button class="button primary" type="submit" onclick="scrollToFirstError();">Submit</button>

Call this function to scroll the page to the first element with the field--error class.

It'll also set focus on the first element if finds with the field--input class.

function scrollToFirstError() {
let errors = document.getElementsByClassName("field--error");
if (errors.length > 0) {
window.scrollTo({
top: errors[0].offsetTop,
behavior: "smooth",
});
errors[0].getElementsByClassName("field__input")[0].focus();
}
}