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 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


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