1

I have already checked a few questions in SO and over the Internet about this issue.

My problem statement is following: I have a gaming site which refreshes based on user action, and when it refreshes I want the user to be scrolled to a location that was decided before reload based on user action.

How I do it is, before reloading the page I store the calculated offset to localStorage.

window.onbeforeunload = function(){
    var scrollTo = calculateNextLoadPosition();
    //below function validates & calls localStorage.setItem(name,value);
    storeLocalData("scrollTo",scrollTo);
    console.log("Stored scrollPosition "+ scrollTo);
};

When page refreshes, I read this localStorage value and scroll page to that offset.

$(function() {
   //retrieve the stored scroll offset as an integer
   var scrollTo = parseInt(getLocalData("scrollTo"));
   $('html,body').scrollTop(scrollTo);
   console.log("Scrolled to "+scrollTo); 
   //also tried..
   //$(window).scrollTop(scrollTo);
   //$(document).scrollTop(scrollTo);
}

When I reload browser with this script, the calculated offset is always correct, the value in browser localstorage is also correct when I examine it using developer tools. But the browser never scrolls to that location even though in console it writes that it has scrolled to that position. It just stays at the top.

Additional info:

  • I do not have overflow-x or overflow-y anywhere in the HTML
  • It works like aa charm in Firefox
  • It is driving me nuts and I am about to chew on my hat in frustration!

Any pointers on what is going wrong is greatly appreciated!

Community
  • 1
  • 1
Undefined Variable
  • 4,196
  • 10
  • 40
  • 69
  • A lot of resources available just by googling, apart from SO posts here's a decently recent one from jquery forum - http://forum.jquery.com/topic/scrolltop-is-not-working-in-chrome – jkris Jan 14 '16 at 17:13
  • @jkris: thank you for your comment, I tried that and a bunch of other scroll plugins to no avail, before I decided to post in SO. In any case, I only need a simple scroll without animations, so I do not want to use a plugin. – Undefined Variable Jan 14 '16 at 17:16
  • Have you tried a small delay before scrolling? – Teemu Jan 14 '16 at 17:20
  • yes, I tried wrapping the call inside window.setTimeout and tried delays from 10 ms to 2 sec...again to no avail :( – Undefined Variable Jan 14 '16 at 17:21
  • A simplified example seems to work at [jsFiddle](https://jsfiddle.net/scuj16sg/1/). Have you tested with a hardcoded value? – Teemu Jan 14 '16 at 17:28
  • @Teemu: one more thing I observed: the scrollTop() works if I type it in console! – Undefined Variable Jan 14 '16 at 17:44

0 Answers0