DEV Community

Wai Liu
Wai Liu

Posted on • Originally published at waiholiu.blogspot.com on

How to maintain the scroll position of the page after client side validation fails

This was something that I was stuck on for a little while today, I was working on a page at work.

I was working on one particular page that had a number of validators and multiple validation summary objects - both client and server side. One position was that some of the client validations (typically for the ones for the control at the bottom), if it failed validation on the client side, it would take you straight to the top of the page. Kind of disorienting for the user.

A google search indicated it was actually quite a common problem which is documented already by Microsoft and has something to do with the internals with the .NET RequiredFieldValidator which would execute some code within its ScrollTo event.

It seems the MaintainScrollPositionOnPostBack, as indicated by its name only works AFTER postback. Client validation doesn't include postback.

Most suggestions are to simply override the ScrollTo function with a simple JavaScript function like so...

<script type="text/javascript">    window.scrollTo = function() { }</script>
Enter fullscreen mode Exit fullscreen mode

This didn't work for me unfortunately. Whilst it did fix the problem for the RequiredFieldValidators, it resetted the positions for my CustomValidators which were all server side. Have not done any investigation into why that is happening.

My solution in the end was that instead of ensuring it was to override the ScrollTo only on the onClick event of the control that was initialising the validation like so...

onClientClick="window.scrollTo = function(x,y) { return true; };"

So far this seemed to have fixed the problem. However, I only just fixed it today, so time will tell whether it has caused any other unanticipated behavior.

I hope this post is useful.



Top comments (0)