Fun Infused Games  |   Smooth Operator

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

Scrolling to the Top of an AJAX Page
Date 8/18/2008    Tags Web, ASP.net    (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()
{

    setTimeout("window.scrollTo(0,0)",0);

}
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 DotNetKicks.com
0" style="displa


This article has been view 2537 times.


Comments

No comments for this article.


Add Comments

Name *
Website
  Name the animal in the picture below:

*  
Comment *
Insert Cancel
Things To Click


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