Scroll To First Error Message On Page With jQuery And ScrollTo

If you have a large page or form that uses validation on it then you will probably want to tell the user that something is going on. One way to do this is by telling the user at the top of the page that something has gone wrong and then letting them figure out where.

A more elegant solution is to scroll the page down the just above the first error message so that the user is aware of what they need to fill in. This can easily be done through a combination of jQuery and the ScrollTo plugin.

The first thing you need on the form is add some tags as the error output elements. Make sure that these tags don't get printed if there are no errors. I have chosen to use p tags with the class of error. Download this plugin and include it within your page.

There was a problem with this element.

All that is needed now is to tell ScrollTo that we want to scroll to the first error message on the screen. We can do this by using the filter "p.error:1" which will find the first p tag with a class of error on the page. You could also use the ":first" filter instead of this, but both have the same outcome.

This gets passed to the ScrollTo plugin in the following way.


The slight problem here is that this scrolls the page down so that this element is flush with the top of the page, which makes sense if the error is above the element. If the error is below the element then you will need to set and offset so that there is enough space between the top of the page and the error message to fit the form element in. This is done through use of the offset option and a negative value, like this.

$.scrollTo($('p.error:1'), {offset: {top:-200}});

The good thing about this is that you can add to any form quite easily and it will have no effect unless there is a paragraph tag with a class of error.


Keep posting stuff like this i really like it

Couldn't you just give the error message an ID and use a hash tag? Inputs should have IDs as a rule, you could also use those.




actually my jquery had a problem with 1 at the end of $.scrollTo($('p.error:1'));

Add new comment

The content of this field is kept private and will not be shown publicly.
5 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.