Friday, October 26, 2007

MAINTAINING SCROLL POSITION IN A WEB USER INTERFACE IN ASP .NET

Some people have problems in maintaining scroll position for a web page after a post back is performed. I had posted an article in PHP example, Maintaining Scroll Position in a Web User Interface in PHP last time.

There is a very simple solution to apply this in ASP .NET. You can just turn on the “Smart Navigation” in the Properties of ASP .NET. But sometimes it can mess up with other JavaScript. Alternatively, you can just add a Java Script to keep the scroll position.

Similar with PHP example, firstly, you need two hidden fields in your form to store the position of X and Y every time a post back is performed. Other than that, you also need two Java Script methods. One is save the position before the page is refreshed; one is set the position X and Y when it is refreshed. Here is the example:
<HTML>
<HEAD>
<TITLE>Maintain Scroll Position</TITLE>

<script>
function SavePos() {
document.Form1.posX.value = document.body.scrollLeft;
document.Form1.posY.value = document.body.scrollTop;
}
function SetPosition() {
var x, y;
x = document.Form1.posX;
y = document.Form1.posY;
if (x != 'undefined' && y != 'undefined')
{
window.scroll (x.value, y.value);
// either use scroll, scrollBy or scrollTo
}
}
</script>

</HEAD>
<BODY onload="SetPosition()">

<form id="Form1" method="post" runat="server"
onsubmit="SavePos();">
<input name="posX" id="posX" type="hidden"
value="0" runat="server" />
<input name="posY" id="posY" type="hidden"
value="0" runat="server" />
<p> A very long page……</p>

<P> A very long page……</P>

</form>

</BODY>
</HTML>

0 comments:

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template