开发者

Maintain scrollbar position upon page reload

I would like to have the table content to go to the same position that it had before the page is开发者_高级运维 refreshed rather than go to the top of the table content. In other words, if the user scrolls down, and a button triggers a page reload, I want table content to come back to the same position after the refresh.

CSS used for my table is

#invoice_incomplete {width:850px;height:400px;overflow:auto;}


As Chinmayee points out, scrolling programmatically is fairly simple. The other part of it is how to record the scroll position before the reload.

I would try an unload handler to write a cookie to record the current scroll position (document.getElementById("invoice_incomplete").scrollTop), but my guess that unload is too late, and not all browsers will succeed in writing the cookie. So probably onbeforeunload is the better event to go with.

So it would be something like this:

window.onbeforeunload = function() {
  document.cookie = "invoiceScrollPos=" + (document.getElementById('invoice_incomplete').scrollTop) + ";path=/";
}

Then after the page reloads, read the value of that cookie and set the scrollTop.

One (probably) undesirable side effect of this approach is that if the user leaves this page, then returns to it later in the same browser session, the scroll position will be restored to what it was before. To address that, you can add an expiration date to the cookie that is perhaps 1 minute after the cookie was created.


You can achieve this using Javascript. On page load you can write [if table has scroll bar]

document.getElementById("invoice_incomplete").scrollTop = 200px; // where you want scroll

or for your entire page write,

 document.body.scrollTop = 200px; // 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜