Scrolling to the Top of an AJAX Page
One of the nice things about creating an Ajax-enabled website is that by default it maintains the scroll position for the user. So if a user were to click a
button halfway down the page, they'll still be halfway down the page when the browser refresh completes. While this is nice in most instances, you might
find yourself with the need to scroll back up to the top of the page.
tutorials you'll find online for handling just this problem), it does not.
Thankfully the solution isn't far off. Instead of scrolling right off the bat, you must create a function that calls the scroll after a short timeout. That
function would probably look a little something like this:
When set, this function will call the window.scroll function zero milliseconds after the page is loaded (I did say short timeout). To call that, you can
use RegisterStartupScript at the end of your function that does a postback.
ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "ResetScrollPosition();", true);
Persumably, this allows the script to run after the AJAX call to set scroll position. You'll notice a similar behavior when trying to set initial focus of
many AJAX pages too and this technique will work there as well. You may run into issues setting focus of a control on the initial page load... if that's
the case, set the timeout value to something higher than zero, I like 500 myself because I know it works and reminds me of the amount of money I wish someone would give me.
This article has been view 2537 times.