When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article
Jobs
















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this Page!

Windows Systems Administrator
Jupitermedia
US-CT-Darien

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, November 17, 2004

Maintaining Scroll Position on Postback
By Steve Stchur


Maintaining Scroll Position Across Postbacks in ASP.NET 2.0
The techniques discussed in this article were designed for ASP.NET version 1.x. While the code, as-is, will work in ASP.NET 2.0, ASP.NET 2.0 offers a built-in mechanism for maintaining scroll position across postbacks. See Client-Side Enhancements in ASP.NET 2.0 for more information!

Introduction
A few months ago, I was asked by my company to post a list of frequently asked questions about our software on our Support Site. I figured this would be a cinch and said "sure, send me the questions and I'll take care of it." Little did I know that we had so many questions in our FAQ list, but I figured "ok, this is just more tedious than anything -- still not terribly difficult." I set about trying to come up with a way to display the questions in a neatly readable fashion, but I was disappointed with virtually every layout that I tried. I thought about it for a bit and came to the conclusion that it would be nice if I displayed only the questions (not the answers) at first. Then, once a question was clicked, it's answer would appear directly beneath the question, pushing all subsequent questions down on the page.

Armed with my new plan, I figured "great, this should be no problem with a little bit of C# code and some server side ASP.NET Panels." To make this concept a bit more reusable, I decided to wrap it up into an ASP.NET server control that I called SlinkyList (because it expands and contracts as you click on the various links). It didn't take too long to get the control written, and initially I was very pleased with it, but then I ran into another problem: since the code that would show/hide the panels executed server-side, this meant that the page would postback each time a question link was clicked. The main problem with this technique was that when a user scrolled down to the bottom of the FAQ and clicked on a question link, the page would postback, and the question's answer would indeed expand, but due to the page postback, the browser would automatically reset the scroll bar to the top of the page. Thus, the answer that had just been expanded was still essentially invisible.

This was clearly not a very user friendly and, as far as I was concerned, totally unacceptable. I did a small bit of research and found out that ASP.NET offers a means to retain scroll position through a mechanism called SmartNavigation. To enable SmartNavigation on a page, you only have to add an attribute to the @Page directive like so: <%@ Page SmartNavigation = "true" %>. But, can you guess that problem with this solution? It only works with Internet Explorer 5.5 or later. Also, many others have reported "issues" with SmartNavigation.

Eventually I came up with a simple solution for maintaining scroll position, one that works in a myriad of browsers. My technique involves the use of a simple custom control, SmartScroller, that will automatically persist scroll position across postbacks once this control is added to a Web Form. (You can check out a live demo to see it in action.) In this article we'll look at how to use SmartScroller, as well as the control's source code.

- continued -

A Technique for Maintaining Scroll Position
Modern browsers provide properties to determine the horizontal and vertical scroll positions, as well as functions to automatically set the scroll position. These properties and functions can be accessed through client-side JavaScript code. In order to maintain scroll position across postbacks, what we need to do is the following:

  1. Whenever the scroll position changes, we need to record the new scroll position in hidden <input> fields.
  2. When the Web Form is posted back, these hidden <input> field values will be sent back to the Web server along with the other form fields. In our server-side code, we need to send back client-side code that sets the browser's scroll position to this sent-back scroll position value.
Through this mechanism we can maintain scroll position across postbacks. However, accomplishing this presents a couple of challenges:
  1. How do we determine from client-side code when the browser's scroll position changes?
  2. What client-side code is needed so that this technique is compatible with the widest array of browsers?
  3. How do we have our server-side code pick out the old scroll values and emit the right client-side code to "reset" the page back to the previous scroll position?
Before we answer these questions, let's first take a look at what client-side JavaScript is needed in order to accomplish maintenance of scroll position:

<script language = "javascript">
<!--
   function sstchur_SmartScroller_GetCoords()
   {
      var scrollX, scrollY;
      
      if (document.all)
      {
         if (!document.documentElement.scrollLeft)
            scrollX = document.body.scrollLeft;
         else
            scrollX = document.documentElement.scrollLeft;
               
         if (!document.documentElement.scrollTop)
            scrollY = document.body.scrollTop;
         else
            scrollY = document.documentElement.scrollTop;
      }   
      else
      {
         scrollX = window.pageXOffset;
         scrollY = window.pageYOffset;
      }
   
      document.forms[formID].xCoordHolder.value = scrollX;
      document.forms[formID].yCoordHolder.value = scrollY;
   }
   
   function sstchur_SmartScroller_Scroll()
   {
      var x = document.forms[formID].xCoordHolder.value;
      var y = document.formsformID].yCoordHolder.value;
      window.scrollTo(x, y);
   }
   
   window.onload = sstchur_SmartScroller_Scroll;
   window.onscroll = sstchur_SmartScroller_GetCoords;
   window.onkeypress = sstchur_SmartScroller_GetCoords;
   window.onclick = sstchur_SmartScroller_GetCoords;
// -->
<script>

Let's step through this code, starting with the sstchur_SmartScroller_GetCoords() function. The purpose of this function is to grab the current position of the scrollbars (both vertical and horizontal). We start by defining a variable to hold each value, scrollX and scrollY. Next we have a couple of conditional statements to handle browser compatibility issues. The first condition checks to see if we are dealing with Internet Explorer, as document.all is an object specific to IE. So, if document.all exists, the conditional will pass and we'll fall into the body of the if statement. Now, not all versions of IE report the scroll position in the same manner. Therefore, I have another set of conditionals that check whether the version of IE uses document.documentElement.scrollLeft/scrollTop or document.body.scrollLeft/scrollTop. If we're not dealing with Internet Explorer, then virtually every other major browser handles the scroll bar position in the same way: window.pageXOffSet and window.pageYOffset.

Once we've got the scroll position captured in variables, we need to write these values to the hidden <input> fields so they can be retrieved on a post back. The names of the hidden <input> fields are xCoordHolder and yCoordHolder, as we'll see shortly.

Once we've got the values stored in the Hidden Text Fields, we're finished with the GetCoords() function. Next up is the sstchur_SmartScroller_Scroll() function. This function is considerably simpler, and is executed when the page loads, resetting the scroll position to the position prior to the last postback. To accomplish this, all we have to do is get the values we just stored in the hidden <input> fields and then call the window.ScrollTo() function to automatically scroll the window to the correct position.

The last bit of JavaScript content specifies on what client-side events to call these two functions. We obviously want to reposition the scroll bars when the page loads, so we instruct that sstchur_SmartScroller_Scroll() be called when onload event fires - window.onload = sstchur_SmartScroller_Scroll;. The remaining JavaScript ties three client-side events to the GetCoords() function:

  • onscroll - this event fires whenever the scroll position in the browser is changed. You'd think this would be the only event needed, but in my testing some browsers didn't fire this event when scrolling with the keyboard. So I also add:
  • onkeypress - this event fires when any key on the keyboard is clicked. Further testing revealed that some browsers made a distinction between scrolling by clicking and dragging the scroll bars, so to be on the safe side I also added this event:
  • onclick - this event fires whenever the mouse is clicked in the browser's window.
Now, I know what you might be thinking: Isn't that overkill? I mean, we're potentially capturing the scroll bar position at times when it's not even changing (if you click in white space for example) or if you push the tab key to move around a Web Form. That's certainly true, but our options are limited, since the onscroll client-side event does not fire predictably for all browsers. Others have utilized different techniques for recording scroll position; for example, in Justin Lovell's article Keeping Scroll Positions Over Postbacks, he uses a JavaScript timer to record the scroll positions 100 times a second.

Now that we've taken a look at the required JavaScript, let's turn our attention to providing an easily, maintainable mechanism for having pages automatically persist their scroll position across postbacks. In Part 2 we'll look at creating a custom server control that provides this functionality by simply dragging and dropping a control onto a Web Form.

  • Read Part 2!


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article



  • JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Solutions
    Whitepapers and eBooks
    Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
    Microsoft Article: 7.0, Microsoft's Lucky Version?
    Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
    Avaya Article: How to Feed Data into the Avaya Event Processor
    Microsoft Article: Install What You Need with Windows Server 2008
    HP eBook: Putting the Green into IT
    Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
    Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
    Avaya Article: Setting Up a SIP A/S Development Environment
    IBM Article: How Cool Is Your Data Center?
    Microsoft Article: Managing Virtual Machines with Microsoft System Center
    HP eBook: Storage Networking , Part 1
    Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES
    Webcasts
    Intel Video: Are Multi-core Processors Here to Stay?
    On-Demand Webcast: Five Virtualization Trends to Watch
    HP Video: Page Cost Calculator
    Intel Video: APIs for Parallel Programming
    HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
    Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
    MORE WEBCASTS, PODCASTS, AND VIDEOS
    Downloads and eKits
    Sun Download: Solaris 8 Migration Assistant
    Sybase Download: SQL Anywhere Developer Edition
    Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
    Red Gate Download: SQL Compare Pro 6
    Iron Speed Designer Application Generator
    MORE DOWNLOADS, EKITS, AND FREE TRIALS
    Tutorials and Demos
    How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
    eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
    IBM Article: Collaborating in the High-Performance Workplace
    HP Demo: StorageWorks EVA4400
    Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
    Microsoft How-to Article: Get Going with Silverlight and Windows Live
    MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES