How to reset scroll position after an UpdatePanel post back?

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

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

ASP.NET Web Forms Bootstrap

More on Bootstrap 4 modals in ASP.NET Web Forms applications using UpdatePanels

by John Avis | April 9, 2019

In this, my third post on this topic, I go over the methods I am using now and the problems I have encountered and overcome.


ASP.NET Web Forms Classic ASP

Custom error pages for ASP.NET Web Forms and Classic ASP in IIS 7 and 8.5

by John Avis | February 20, 2019

I was recently doing some work on a website which has a mixture of older Classic ASP pages and ASP.NET Web Forms pages and ran into problems with custom error pages.


ASP.NET Web Forms

Nicer localised UpdateProgress’ for your ASP.NET pages with multiple UpdatePanels

by John Avis | February 9, 2018

On an ASP.NET Web Forms page with multiple UpdatePanels it’s nice to give the user some feedback when one of the panels is being updated.

Comments

David

by David | November 2, 2016

Very useful - thanks

Reply

Leave a Comment
Tags
ASP.NET Html Forms ASP.NET MVC ASP.NET Web Forms ASP.NET Web Pages Bootstrap C# Classic ASP Cool Websites Databases eBay and PayPal Electrical Repairs General Hardware HTML/CSS Jquery/Javascript Media Center Mobile Phones Responsive Web Design SEO and Social Networking Web Design Web Development Web Security web+db Website Hosting Windows XP Youtube

About me

...mostly about web development and programming, with a little bit of anything else related to the Internet, computers and technology.

Subscribe

Get the latest posts delivered to your inbox.