0

I've been searching for hours and have come up empty.

I'm detecting the users scroll position on beforeunload and saving it to a cookie (using the plugin). After a page refresh the page should now scroll to this position, however it does not.

I can see that the position is saved, and I can also read it inside an alert().

scrollTop works with "hard numbers" but not with the data from the cookie.

parseInt also doesn't help.

Any ideas why? Thanks a lot in advance!


This code isn't working:

window.onload = function() {
    setTimeout(function() {
    $(document).scrollTop(300);
}, 100);

this works

vari = $.cookie("scrollTil");

window.onload = function() {
    setTimeout(function() {
    $(document).scrollTop(vari);
}, 100);

ED:

$(document).ready(function(){

vari = $.cookie("scrollTil");

window.onload = function() {
    setTimeout(function() {
        $(document).scrollTop(vari);
    }, 100);
}

$(window).unload(function(){
    $.cookie("scrollTil", $(window).scrollTop());
})
});
  • if you console.log(vari) what do you get – Kai Qing Apr 12 '13 at 01:39
  • I get a number, so it should work. If i set vari=300 scrolltop works, so I have no clue. – John Porlarn Apr 12 '13 at 01:43
  • Yeah, scrollTop will work with int or string. Your sample code is missing the closing } for the onload function. but that may just be because you didn't post the whole thing. Strange. – Kai Qing Apr 12 '13 at 02:00
  • Yeah I just posted without the } ^^ Also when i typeof(vari) i get number, so it is very weird. Thanks for helping – John Porlarn Apr 12 '13 at 02:02
  • Seems to work fine in this fiddle. Seems like you have a problem elsewhere, likely where it's setting the cookie? http://jsfiddle.net/ryanbrill/WxKgx/ – ryanbrill Apr 12 '13 at 02:10
  • You're right, like that it's working. So manually setting the cookie works. However, when I update the cookie with jquery by scrolling down and refreshing, I get different values the further I scroll - as expected. But when I pass it to `scrollTop` it doesn't work. `$.cookie("scrollTil", $(window).scrollTop());` sets the cookie correctly, but doesn't work with `scrollTop`. `$.cookie("scrollTil", 300);` sets to 300 (not mouse pos. ofc) but works. I made an edit with full code. – John Porlarn Apr 12 '13 at 02:29

1 Answers1

0

Your code is fine. But it did not work like you expected because $(window).scrollTop() that you called in $(window).unload(function() always return 0.

You should capture the scroll position when user done scrolling. You can find workaround here

Javascript: do an action after user is done scrolling

Community
  • 1
  • 1
Telvin Nguyen
  • 3,569
  • 4
  • 25
  • 39