Keeping scroll position

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I want to keep the scroll position after reload. I tried this:

function f_scrollTop() {
 // returns scroll position

function scrollPosition() {
 document.buy_from_shop_form.scrollpos.value = f_scrollTop();

<form name="buy_from_shop_form" id="buy_from_shop_form" method="post"  
        <input type="hidden" name="cd_price" id="cd_price" value="<?php echo  
$rel[8]; ?>" />
        <input type="hidden" name="cd_id" id="cd_id" value="<?php echo  
$rel[0]; ?>" />
        <input type="hidden" name="scrollpos" id="scrollpos" value="" />
        <input type="submit" name="buy_from_shop_submit"  
id="buy_from_shop_submit" value="Buy CD" onClick="scrollPosition()" />

It didn't work. When I did a print_r($_POST), the scrollpos field did not  
contain anything. So I tried saving the scroll position in a cookie instead:

function scrollPosition() {
 document.cookie = 'sp=' + f_scrollTop();

print_r($_COOKIE) revealed that the scroll position was stored in the  
cookie. I removed the scrollpos hidden field from the form and added this  
code to the script:

if(isset($_COOKIE['sp'])) {
 echo "<script type = 'text/javascript'>\n";
 echo "window.pageYOffset=".$_COOKIE['sp'];
 echo "</script>";

When that did not work, I tried

echo "document.documentElement.scrollTop = " . $_COOKIE['sp'];

instead, and when that didn't work either, I tried

echo "document.body.scrollTop = " . $_COOKIE['sp'];

which also did not work.

I suspect the reason I cannot get this to work is that I haven't properly  
understood how Php and Javascript are parsed/processed/rendered. I have  
searched the Web for articles about it, but none of the articles I found  
were detailed enough to give me a thorough understanding of the mechanisms.

Help would be greatly appreciated.  

Re: Keeping scroll position

Lancelot wrote:

Quoted text here. Click to load it


Understanding JS and PHP interact is very simple if you follow these 3  
1) Always check the HTML-source produced by PHP
2) Always check the HTML-source produced by PHP
3) Always check the HTML-source produced by PHP

From a browsers point-of-view there is little/no difference if PHP produced  
the HTML, or a blue goblin did.
So try to make a plain HTML-version first that gets the job done.
THEN think about PHP automating that job.

Erwin Moller

Site Timeline