Fun Infused Games  |   Smooth Operator RSS 

  Home   |    Archive   |    Subscribe   |    Search   |    About
Posts prior to 8/2/2010 may be missing data. If you need one of those posts, please contact and I will try and recover/find it.

Scrolling to the Top of an AJAX Page
Date 8/18/2008    Tags Web,    (0)

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.

You'd think that inserting the JavaScript function "window.scrollTo(0,0)" as a startup script would do this for you, but (despite the claims of multiple 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:
function ResetScrollPosition()


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.

kick it on
0" style="displa

This article has been view 2537 times.


No comments for this article.

Add Comments

Name *
  Name the animal in the picture below:

Comment *
Insert Cancel

Xbox (1)  C# (14)  Visual Studio (1)  Cool (2)  iOS (3)  PC (1)  Rant (50)  Sports (11)  XBLIG (32)  Abduction Action (1)  Design (2)  Fin (1)  Volchaos (11)  VolChaos (1)  Nastier (4)  Game Dev (11)  Abdction Action! (1) (18)  Nasty (34)  SQL (1)  XNA (40)  World of Chalk (2)  Video Games (7)  Web (19)  Abduction Action! (27)  Hypership (28)  WP7 (8)  Advise (14)  FIN (20)  Trivia or Die (3)  Development (13)  Absurd (2)  Trivia Or Die (1)