Thursday, October 25, 2007

MAINTAINING SCROLL POSITION IN A WEB USER INTERFACE IN PHP

Anyone who is creating a very long Web Form that entails a lot of post backs may encounter to the user interface problem that occurs in such scenario that loss of scroll position on each post back (namely, if you scroll down to the middle of a long page, and after the browser refreshed, the scroll position is lost).

For this case, using Java Script for keeping the scroll position is the best way to go. Java Script can help us to know the current position of the browser.

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 name="Form1" id="Form1" method="post"
onsubmit="SavePos()" action="index.php">
<input name="posX" id="posX" type="hidden"
value="<?php echo $_REQUEST['posX'] ? >" />
<input name="posY" id="posY" type="hidden"
value="<?php echo $_REQUEST['posY'] ? >" />
<p>A very long page……</p>

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

</BODY>
</HTML>

Good Luck!

2 comments:

Anonymous said...

Your blog keeps getting better and better! Your older articles are not as good as newer ones you have a lot more creativity and originality now keep it up!

xiaoyu on January 8, 2010 at 1:56 PM said...

thanks for your comment. :)

 

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