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!