Skip to content Skip to sidebar Skip to footer

Reload Page In Same Position

Hi I wanted to know if there was an easy way to scroll a page to its previous position when it reloads. For example I have a bulletin board half way down my page. The bulletins a

Solution 1:

You can use an html anchor to scroll to part of a page:

index.php?page_num=2#YOURID

Or set it using your js. location.hash

Solution 2:

I took the code from http://webcodingeasy.com/Javascript/Get-scroll-position-of-webpage--crossbrowser and use it to set the scroll to the last position on page reload.

<script type="text/javascript">
<!--
/////////////////////////////////////////////////////////
//get scroll position
var get_scroll = function(){
var x = 0, y = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    y = window.pageYOffset;
    x = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    y = document.body.scrollTop;
    x = document.body.scrollLeft;
} else if( document.documentElement && 
( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    y = document.documentElement.scrollTop;
    x = document.documentElement.scrollLeft;
}
var obj = new Object();
obj.x = x;
obj.y = y;
return obj;
};
//////////////////////////////////
function saveScroll(){
var scroll = get_scroll(); 
document.getElementById("x").value = scroll.x;
document.getElementById("y").value = scroll.y;
}
//////////////////////////////////////////////
////////This runs at <body onload = "setScroll()" >///////////////////////////
function setScroll(){
var x = "<?php echo $_POST['x']; ?>";
var y = "<?php echo $_POST['y']; ?>";

if(typeof x != 'undefined')
window.scrollTo(x, y);
}
////////////////////////////////////////////////////////////////
-->
</script>

<body onload = "setScroll()">

<!--Post variables to save x & y -->

<input name="x" id="x" type="hidden" value="" />
<input name="y" id="y" type="hidden" value="" />
</body>

Then use an event such as onclick="saveScroll()" or to save the scroll values. After submit watch the magic happen! :)

The function to retrieve scroll positions was taken from: http://webcodingeasy.com/Javascript/Get-scroll-position-of-webpage--crossbrowser

Solution 3:

The hard way you mentioned might be the only way to do it, since from the browser's perspective, it is loading an entirely new page.

Another way around it, though, would be to load the next next page of bulletins via an XHR and just replace the current contents of the div that the bulletins are in. That would make paging back and forth a seamless experience for your users, as they wouldn't have to wait for a whole page to load and render. This may or may not be a good choice depending on the circumstances, but it's worth considering.

Post a Comment for "Reload Page In Same Position"