Tuesday, August 19, 2008

Move to anchor after postback

You can add anchor tags in the URL to move the scroll bar to a specific section of the web page.
Example : http://www.w3.org/TR/html401/struct/links.html#h-12.2.1

But how we can do the same after a postback. I am not talking about MaintainScrollPositionOnPostback. It will just move the scroll bar position to the previous state after the postback.

Our aim is to move the scroll bar to a custom position using anchor tags.

1. Set MaintainScrollPositionOnPostback="false" in the @Page directive.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="view_Default1" Title="Untitled Page" MaintainScrollPositionOnPostback="false" %>

2. Create a named anchor in the HTML.
<a name="MOVEHERE"></a>

3. Write the follwoing code in the page load.
if (IsPostBack)
ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#MOVEHERE';", true);
Please note I wrote the code inside IsPostback.

Thats all. Now test the page and you can see the page automatically move to the #MOVEHERE anchor when the page loads after a postback.

The javascript code location.hash = '#MOVEHERE'; did the trick.

I have tested it in IE 6, FF 2.x, Apple Safari for Windows and Opera.