How to reset scroll position after an UpdatePanel post back?

John Avis by | June 6, 2014 | ASP.NET Web Forms Web Development

If you use ASP.NET UpdatePanels, most of the time you want to maintain the window scroll position but there are occasions when you don't want to scroll back to the top or to a specific control.
If you use ASP.NET UpdatePanels, most of the time you want to maintain the window scroll position but there are occasions when you want the page to scroll back to the top or to a specific control. For example, when you have a paging control you should return the user to the top of the list.

It is quite simple to accomplish this using the ScriptManager's registerStartupScript method.

To reset the scroll position (back to top), add the following code to your postback event:

ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "ScrollTop", "setTimeout('window.scrollTo(0,0)', 0);", true);

If you use jQuery you can use the following code to scroll to the top of a specific element (with the ID mydiv in this example), no plugin required:

ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "ScrollTop", "setTimeout(\"$('html, body').scrollTop($('#mydiv').offset().top)\", 0);", true);

Using jQuery opens up many other options, including animating the scroll position.

NB. In the above examples change UpdatePanel1 to the ID of your UpdatePanel.

If this tip helped you please share on Facebook, Twitter or Google+.

Related Posts

Computers & Internet Web Development Website Hosting

500 Internal Server Error after migrating from IIS 7.5 to IIS 10

by John Avis | November 4, 2019

As support ends for Microsoft Windows Server 2008 I have recently gone through migrating some websites to a new server running Windows Server 2016 and IIS 10 but some of the websites did not work.


Jquery/Javascript Web Development

tagInput: A simple jQuery plugin for tag entry using Bootstrap 4

by John Avis | October 15, 2019

For a website project I needed a way to enter multiple tags. I just wanted something simple that I could easily modify to suit my own needs, so I wrote my own.


ASP.NET Web Forms Web Development

ASP.NET bug with RadioButton GroupName in Repeater

by John Avis | September 1, 2019

I rediscovered a bug in ASP.NET that affects RadioButtons inside repeaters. Here is my solution to the problem.

Comments

David

by David | November 2, 2016

Very useful - thanks

Reply

Leave a Comment

Tags

About me

...random postings about web development and programming, Internet, computers, electronics and automotive topics.

Subscribe

Get the latest posts delivered to your inbox.