Keep Your Scroll Position After Postbacks

Posting back to the server can rob your browser of its scroll position, but it doesn't have to.

Hot Tip

LANGUAGES: C# | JavaScript

TECHNOLOGIES: Postbacks | HTML

 

Keep Your Scroll Position After Postbacks

Posting back to the server can rob your browser of its scroll position, but it doesn't have to.

 

By Jeff Prosise

 

ASP.NET programmers often bemoan the fact that posting back to the server makes the browser lose its scroll position, causing the page to scroll back to the top. Here's a solution that relies on client-side JavaScript to transmit the current scroll position - along with the form's other postback data. It then writes out a <body> tag containing an onload attribute, which restores the scroll position following a postback. In other words, it prevents the page from scrolling back to the after clicking on a submit button. Try this code:

 

<%@ Page Language="C#" %>

 

<html>

  <%

    if (Request["__SCROLLPOS"] != null &&

     Request["__SCROLLPOS"] != String.Empty) {

       int pos = Convert.ToInt32 (Request["__SCROLLPOS"]);

       Response.Write ("<body id=\"myBody\" " +

        "onload=\"javascript:myBody.scrollTop=" +

        pos + ";\">");

    }

    else

       Response.Write ("<body id=\"myBody\">");

  %>

    <form id="myForm" onsubmit=

     "javascript:return onSubmitForm ();" runat="server">

        <input type="hidden" name="__SCROLLPOS" value="" />

        <!-- Insert other form content here -->

        <asp:Button Text="Test" RunAt="server" />

    </form>

  </body>

</html>

 

<script language="javascript">

function onSubmitForm ()

{

    myForm.__SCROLLPOS.value = myBody.scrollTop;

    return true;

}

</script>

 

To see for yourself, add enough content to the page to cause a scrollbar to appear. Then scroll to the bottom of the page and click on the Test button; the scroll position will be preserved.

 

This technique's chief limitation is it works only when the postback is generated by a Button control. Other controls that force postbacks - controls such as LinkButton and Calendar - generate postbacks programmatically, which prevents the onSubmitForm function from being called. Still, this technique is very useful for forms containing conventional push buttons.

 

Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET.

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish