views:

69

answers:

1

I'm using the following jQuery Javascript to save the scrollbar position before the unload event and reapply it again:

$(document).ready(function () {
    document.documentElement.scrollTop = $.cookie("scroll") || 0;
});

window.onbeforeunload = function () {
    $.cookie("scroll", document.documentElement.scrollTop, { expires: 7 });
}

Basically I have a series of links that refresh the page and I would like the browser to restore the scrollbar position. Note I cannot use AJAX in this instance. It works a treat in Firefox. In Chrome and Safari however it only works when the browser window is refreshed, and not when the link is clicked to refresh the page. It's as if clicking the link isn't being recognised as onbeforeunload.

I have tried to modify the code to set the scroll cookie using a click event as follows with no luck:

$(document).ready(function () {
    document.documentElement.scrollTop = $.cookie("scroll") || 0;
});

$('a.lockscrollbar').click(function() {
    $.cookie("scroll", document.documentElement.scrollTop, { expires: 7 });
}

FYI I'm using jQuery 1.4.2 with the jQuery cookie plugin.

Any ideas?

A: 

Scrolling the <body> in Chrome and Safari doesn't work very well, or possibly at all. I don't know why but I once had a similar problem and I fixed it by using a <div> nested inside the <body>.

Pointy
It's odd that it works perfectly when refreshing the window, but not following a link. I'm starting to think that in this instance it's a problem with onbeforeunload and not ScrollTop.
Paul
Well, investigate to your heart's content, but you might want to see if wrapping all your page content in another `<div>`, and then scrolling that instead of the `<body>`, makes a difference.
Pointy