Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Saturday, September 02, 2006

Maintaining Scroll Position on Postback

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.

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?

Continue from 4Guys…

Post a Comment