problem while using Javascript to maintain scroll position after page reload in a dynamic(PHP) webpage.

az9214
az9214 used Ask the Experts™
on
Hi there,

I am trying to get a php page to maintain scroll position after the page has been reloaded.
The page reloading is done using javascript and the code i have implemented so far in order to maintain the scroll position is also written using javascript. Here are some snippets of the code

function productQty(prodid,cpath){
setCookie('divid',prodid);
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

window.onload = function(){
var divid=getCookie('divid');

var objDiv = document.getElementById(divid);

objDiv.scrollTop = objDiv.scrollHeight;

}

and heres an example of a div that i am trying to get the page to scroll down to.

<div id="708"> <input type="text" style="width:40px;" name="order_product[708]" class="check_cp_input" value="" title="48" /> </div>

and this is where the javascript function store the div cookie is called

<div onclick="return productQty(708,16);"  ><img src="images/buynow.jpg" border="0" style="cursor:pointer;"/> </div>

So far, the page does not scroll down to the supplied div on reload and i do not know what i am doing wrong. Any help into
understanding the problem will be greatly appreciated.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2009
Commented:
instead of
var objDiv = document.getElementById(divid);
objDiv.scrollTop = objDiv.scrollHeight;

give this a shot
var objDiv = document.getElementById(divid);
objDiv .scrollIntoView(true);

https://developer.mozilla.org/En/DOM/Element.scrollIntoView

Author

Commented:
Thank you.
The solution works.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial